这是我试过的解决方案,但是它是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/