Swift按照数组元素出现的次数及大小排序

前端之家收集整理的这篇文章主要介绍了Swift按照数组元素出现的次数及大小排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

要求如下:

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
    }
}

注意后一种解决办法只能在Swift2.x中运行,如果要在Swift3中运行需要略做修改,请参考我写的另一篇博文:

Swift3中如何为Array写一个限定Type的扩展

原文链接:/swift/323342.html

猜你在找的Swift相关文章