Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - Вернуть K самых повторяющихся элементов
- func topKFrequent(_ words: [String], _ k: Int) -> [String] {
- var dict = [String:Int]()
- var result = [String]()
- for st in words {
- dict[st, default: 0] += 1
- }
- let sorted = dict.keys.sorted {
- // Если частота встречаний одинакова, то по лексикограф порядку
- if dict[$0] == dict[$1] {
- return $0 < $1
- } else {
- return dict[$0]! > dict[$1]!
- }
- }
- // k не включаем так как с 0 начинаем
- for i in 0..<k {
- result.append(sorted[i])
- }
- return result
- }
- topKFrequent(["i","love","leetcode","i","love","coding"], 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement