繁体   English   中英

如何使用时间复杂度<O(n ^ 2)和空间复杂度O(n)快速按值对整数数组进行排序,然后按重复次数对整数数组进行排序

[英]How to sort array of integer first by value and second by number of repetition using swift in time complexity < O(n^2) and space complexity O(n)

这是我尝试过的解决方案,但是顺序为O(n ^ 2),所以没有通过测试结果

func sortArrayByValueAndByFrequency(nums : [Int]) {
    var countDict = [Int : Int]()
    var count  = Int()
    var values = Int()
    var output = [Int]()
    for index in 0 ..< nums.count {
        for index2 in 0 ..< nums.count{
            if nums[index2] == nums[index] {
                values = nums[index2]
                count += 1
            }
        }
        countDict[values] = count

        count = 0
    }

    let sortedByKey = countDict.sorted { ($0.key < $1.key)}
    let sortedByValue = sortedByKey.sorted { ($0.value < $1.value)}
    for (k,v) in sortedByValue {
        for _ in 1 ... v {
            output.append(k)
        }
    }

    output.forEach { (orderedNumber) in
        print(orderedNumber)
    }
}

输入/输出示例:

Example array = [1,1,2,3,4,5,5,6,7,7,7,8,9,9,9,20,25,21,20]
Expected output = [2,3,4,6,8,21,25,1,1,5,5,20,20,7,7,7,9,9,9]

example 2 = [1,2,3,4,4,3,3]
output = [1,2,4,4,3,3,3]

这个问题是在HackerRank上问我的

首先确定每个值的出现次数(O(n)),然后对这些值进行排序,并以出现次数为第一排序标准,并将值本身作为第二排序标准(O(n log(n)) )。 通过元组比较方便地进行排序 (比较Swift-使用多个条件对对象数组进行排序 ):

let array = [1,1,2,3,4,5,5,6,7,7,7,8,9,9,9,20,25,21,20]

let countDict = array.reduce(into: [Int:Int]()) {
    $0[$1, default: 0] += 1
}

let sorted = array.sorted(by: {
  (countDict[$0]!, $0) < (countDict[$1]!, $1)
})

print(sorted)
// [2, 3, 4, 6, 8, 21, 25, 1, 1, 5, 5, 20, 20, 7, 7, 7, 9, 9, 9]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM