|
| 1 | +// MARK: 리뷰를 받고 시도해본 다른 풀이 (time: O(n), space O(n) |
| 2 | +class Solution { |
| 3 | + func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { |
| 4 | + // 빈도수 별로 Dictionary에 저장 |
| 5 | + var dict = [Int: Int]() |
| 6 | + for num in nums { |
| 7 | + dict[num, default: 0] += 1 |
| 8 | + } |
| 9 | + // Bucket sort 사용, 크기는 nums 만큼, 빈도수가 nums 공간보다 클수는 없으니까 |
| 10 | + var bucket = Array(repeating: [Int](), count: nums.count + 1) |
| 11 | + for (key, value) in dict { |
| 12 | + // 빈도수를 인덱스로 key == num 을 저장함 |
| 13 | + // 배열로 한 이유는 빈도수가 같은게 있을 수 있으니까! |
| 14 | + bucket[value].append(key) |
| 15 | + } |
| 16 | + |
| 17 | + // 결과 출력 |
| 18 | + var answer = [Int]() |
| 19 | + // bucket의 뒤에서부터 탐색 |
| 20 | + for index in stride(from: nums.count, to: 0, by: -1) { |
| 21 | + // 없으면 무시 |
| 22 | + guard !bucket[index].isEmpty else { continue } |
| 23 | + // 버켓의 현재 인덱스에 nil이 아니면 하나씩 결과에 추가해줌. |
| 24 | + for item in bucket[index] { |
| 25 | + answer.append(item) |
| 26 | + // k개 만큼 가져왔다면 바로 리턴 |
| 27 | + if answer.count == k { return answer } |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + return answer |
| 32 | + } |
| 33 | +} |
| 34 | +// MARK: time: O(nlogn), space: O(n) |
| 35 | +// n+nlogn+n |
| 36 | +class Solution { |
| 37 | + func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { |
| 38 | + var dict = [Int: Int]() |
| 39 | + for num in nums { |
| 40 | + dict[num, default: 0] += 1 |
| 41 | + } |
| 42 | + return [Int](dict.sorted{$0.value > $1.value}.map{$0.key}[..<k]) |
| 43 | + } |
| 44 | +} |
0 commit comments