要求如下:
1、已知一个数组,按照单个元素在数组中出现的次数作为重新排序的依据,个数多的排在前面
2、相同个数时候,元素值大的排前面
例子:
[1, 2, 2, 3, 5, 5]
经过计算得到的结果是:
[5, 5, 2, 2, 3, 1]
一种解决方法是:
import UIKit
extension Sequence where Iterator.Element == Int{
private func removeRepeats()->[Int]{
let set = Set(self)
return Array(set).sorted {$0>$1}
}
private func countFor(value:Int)->Int{
return filter {$0 == value}.count
}
func sortByRepeatCount()->[Iterator.Element]{
var wets = [[Int]]()
let clearedAry = removeRepeats()
for i in clearedAry{
wets.append([i,countFor(value: i)])
}
wets = wets.sorted {
$0[1] > $1[1]
}
var result = [Int]()
for x in wets{
let i = x[0]
let count = x[1]
for _ in 0..<count{
result.append(i)
}
}
return result
}
}
var ary = [1,1,2,1,3,3,4,5,4,6,6,6]
print(ary.sortByRepeatCount())
//输出 "[6, 6, 6, 1, 1, 1, 4, 4, 3, 3, 5, 2]\n"
别的网友提供了更直观更简单的方法:
extension SequenceType where Generator.Element : Hashable {
func frequencies() -> [Generator.Element:Int] {
var results : [Generator.Element:Int] = [:]
for element in self {
results[element] = (results[element] ?? 0) + 1
}
return results
}
}
let alpha = [2,8,2,6,1,8,2,6,6]
let beta = [6,6,6,2,2,2,8,8,1]
let sorted = alpha.frequencies().sort {
if $0.1 > $1.1 { // if the frequency is higher, return true
return true
} else if $0.1 == $1.1 { // if the frequency is equal
return $0.0 > $1.0 // return value is higher
} else {
return false // else return false
}
}
注意后一种解决办法只能在Swift2.x中运行,如果要在Swift3中运行需要略做修改,请参考我写的另一篇博文:
时间: 2024-10-10 16:48:21