arrays - 如何在时间复杂度 < O(n^2) 和空间复杂度 O(n) 中使用 swift 首先按值排序整数数组,然后按重复次数排序整数数组

标签 arrays swift sorting swift4

这是我试过的解决方案,但是它是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 - Sort array of objects with multiple criteria ):

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]

关于arrays - 如何在时间复杂度 < O(n^2) 和空间复杂度 O(n) 中使用 swift 首先按值排序整数数组,然后按重复次数排序整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51227525/

相关文章:

regex - 在Matlab中以最通用的方式从char数组中提取数值数组

java - 从用户输入的字符串和 String[][] 的第一列中检索匹配项

javascript - 如何按剩余的月数和天数对列进行排序

c - 使用序列化二叉搜索树对海量数据进行排序

c - 如何将字符串数组中的元素传递给线程?

php - 根据结果​​通过电子邮件发送 PHP

ios - 推送通知在开发中工作正常,但设备在生产中未收到通知

ios - Swift 如何在 AppDelegate 中发送电子邮件 fetch?

ios - 快速创建不区分大小写的字典

c# - 按指定顺序对字符串进行排序