Skip to content

Commit

Permalink
Added Swift 347-Top-k-frequent-elements
Browse files Browse the repository at this point in the history
Swift solution of Top k frequent elements. Leetcode judge accepted the solution.
  • Loading branch information
chandra9302 authored Apr 4, 2022
1 parent 933ca4a commit fb8a33c
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions swift/347-Top-k-frequent-elements.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var count = [Int:Int]()
for n in nums {
guard count[n] != nil else {
count[n] = 1
continue
}
count[n] = 1 + count[n]!
}

var freq = [[Int]](repeating: [], count: nums.count+1)
for (n, c) in count {
freq[c].append(n)
}

var res = [Int]()
for i in stride(from: freq.count-1, to: 0, by: -1) {
for n in freq[i] {
res.append(n)
if res.count == k {
return res
}
}
}
return res
}
}

0 comments on commit fb8a33c

Please sign in to comment.