forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJustHm.swift
More file actions
44 lines (42 loc) ยท 1.59 KB
/
Copy pathJustHm.swift
File metadata and controls
44 lines (42 loc) ยท 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// MARK: ๋ฆฌ๋ทฐ๋ฅผ ๋ฐ๊ณ ์๋ํด๋ณธ ๋ค๋ฅธ ํ์ด (time: O(n), space O(n)
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
// ๋น๋์ ๋ณ๋ก Dictionary์ ์ ์ฅ
var dict = [Int: Int]()
for num in nums {
dict[num, default: 0] += 1
}
// Bucket sort ์ฌ์ฉ, ํฌ๊ธฐ๋ nums ๋งํผ, ๋น๋์๊ฐ nums ๊ณต๊ฐ๋ณด๋ค ํด์๋ ์์ผ๋๊น
var bucket = Array(repeating: [Int](), count: nums.count + 1)
for (key, value) in dict {
// ๋น๋์๋ฅผ ์ธ๋ฑ์ค๋ก key == num ์ ์ ์ฅํจ
// ๋ฐฐ์ด๋ก ํ ์ด์ ๋ ๋น๋์๊ฐ ๊ฐ์๊ฒ ์์ ์ ์์ผ๋๊น!
bucket[value].append(key)
}
// ๊ฒฐ๊ณผ ์ถ๋ ฅ
var answer = [Int]()
// bucket์ ๋ค์์๋ถํฐ ํ์
for index in stride(from: nums.count, to: 0, by: -1) {
// ์์ผ๋ฉด ๋ฌด์
guard !bucket[index].isEmpty else { continue }
// ๋ฒ์ผ์ ํ์ฌ ์ธ๋ฑ์ค์ nil์ด ์๋๋ฉด ํ๋์ฉ ๊ฒฐ๊ณผ์ ์ถ๊ฐํด์ค.
for item in bucket[index] {
answer.append(item)
// k๊ฐ ๋งํผ ๊ฐ์ ธ์๋ค๋ฉด ๋ฐ๋ก ๋ฆฌํด
if answer.count == k { return answer }
}
}
return answer
}
}
// MARK: time: O(nlogn), space: O(n)
// n+nlogn+n
class Solution {
func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] {
var dict = [Int: Int]()
for num in nums {
dict[num, default: 0] += 1
}
return [Int](dict.sorted{$0.value > $1.value}.map{$0.key}[..<k])
}
}