要求如下:
1、已知一个数组,按照单个元素在数组中出现的次数作为重新排序的依据,个数多的排在前面 2、相同个数时候,元素值大的排前面
例子:
[1,2,3,5,5]
经过计算得到的结果是:
[5,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,3,4,5,6,6]
print(ary.sortByRepeatCount())
//输出 "[6,6,1,4,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,6]
let beta = [6,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
}
}