【问题标题】: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)如何使用 swift 在时间复杂度 < O(n^2) 和空间复杂度 O(n) 中首先按值排序整数数组,然后按重复次数对整数数组进行排序
【发布时间】:2018-07-07 22:55:40
【问题描述】:

这是我尝试过的解决方案,但它的顺序是 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 上问我的

【问题讨论】:

  • 你的标题倒退了。给定您的示例数组和示例输出,标题应说明“首先按重复次数,然后按值其次”。
  • 任何有助于解决问题的方法,但我认为我首先按重复 1 的值排序,然后按值排序以获得更高的重复次数。
  • 您的输出按重复次数排序。然后对于具有相同重复次数的那些,您按值排序。这与你的标题相反。如果按照标题中的说明进行排序,则第二部分将无关紧要,因为整个数组将按值排序,这将简单地将其按简单的数字顺序排列。

标签: arrays swift sorting swift4


【解决方案1】:

首先确定每个值出现的次数(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]

【讨论】:

  • 这不是O(1) 而是O(n) 空间?虽然这个限制看起来有点奇怪。
  • @dfri:你说得对,问题中的代码需要额外的字典。我必须承认我没有注意到标题中的限制。
  • 如果我没记错的话(部分是快速排序?),即使 Swifts 自己的排序也会不符合该标准,所以除非 OP 的挑战涉及编写排序算法,否则这可能是一个错误(或缺乏细节)限制。
  • @dfri:它是 introsort(快速排序的一种变体),比较 stackoverflow.com/q/27677026/1187415。如果我没记错的话,那只需要 O(1) 的存储空间。
  • @AshimDahal 如果是这样,请考虑更新您的问题标题,删除O(1) 空间限制,并提供您要解决的问题的链接(Hackerrank / 等?)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 2015-05-25
  • 1970-01-01
相关资源
最近更新 更多