LeetCode-347
Top K Frequent Elements : Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
note : time complexity must be better than O(n log n), where n is the array s size.
Over *
:::python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if len(set(nums))==1:
return [nums[0]]
answer = []
count = collections.Counter(nums).most_common(n=k)
return [i[0] for i in count]
Result : 111ms Memory: 21mb
Top K Frequent Elements
Top K Frequent Elements๋ ์ ์ ๋ฐฐ์ด์์ ๊ฐ์ฅ ๋น๋ฒํ๊ฒ ๋ฑ์ฅํ๋ ์์ K๊ฐ์ ์์๋ฅผ ์ฐพ๋ ์๊ณ ๋ฆฌ์ฆ์ ๋๋ค.
์๋ฅผ ๋ค์ด, [1,1,1,2,2,3]์์ ์์ 2๊ฐ์ ์์๋ฅผ ์ฐพ๋๋ค๋ฉด, 1๊ณผ 2๊ฐ ์ ํ๋ฉ๋๋ค. 1์ 3๋ฒ, 2๋ 2๋ฒ ๋ฑ์ฅํ์๊ธฐ ๋๋ฌธ์ ๋๋ค.
์ด ์๊ณ ๋ฆฌ์ฆ์ hash table๊ณผ heap์ ์ด์ฉํ์ฌ ๊ตฌํํ ์ ์์ต๋๋ค.
- hash table
- ์ ์ ๋ฐฐ์ด์ ์ํํ๋ฉฐ ์์์ ๋ฑ์ฅ ํ์๋ฅผ ์ ์ฅํ๋ hash table์ ์์ฑํฉ๋๋ค.
- ์ ๊ทผ ํ์๊ฐ ๋ง์ ์์ K๊ฐ์ ์์๋ฅผ ์ ์ฅํ ๊ฒฐ๊ณผ ๋ฐฐ์ด์ ์์ฑํฉ๋๋ค.
- hash table์์ ๊ฐ์ฅ ๋ฑ์ฅํ ํ์๊ฐ ํฐ ์์๋ถํฐ K๊ฐ ๊น์ง๋ง ๊ฒฐ๊ณผ ๋ฐฐ์ด์ ์ ์ฅํฉ๋๋ค.
- heap
- ์ ์ ๋ฐฐ์ด์ ์ํํ๋ฉฐ ์์์ ๋ฑ์ฅ ํ์๋ฅผ ์ ์ฅํ๋ hash table์ ์์ฑํฉ๋๋ค.
- hash table์ ๋ฐํ์ผ๋ก heap์ ์์ฑํฉ๋๋ค. heap์๋ ์์์ ๋ฑ์ฅ ํ์๋ฅผ ์ ์ฅํฉ๋๋ค.
- heap์์ ์์ K๊ฐ์ ์์๋ฅผ popํ์ฌ ๊ฒฐ๊ณผ ๋ฐฐ์ด์ ์ ์ฅํฉ๋๋ค.
์ด ์๊ณ ๋ฆฌ์ฆ์ ์๊ฐ๋ณต์ก๋๋ ์ ์ ๋ฐฐ์ด์ ์ํํ๋ O(n)๊ณผ hash table ๋๋ heap์ ์ฌ์ฉํ์ฌ ์์๋ฅผ ์ถ์ถํ๋ O(K log K)์ ๋๋ค. ๋ฐ๋ผ์ ์ ์ฒด ์๊ฐ๋ณต์ก๋๋ O(n + K log K)์ ๋๋ค.
์ ์๊ณ ๋ฆฌ์ฆ์ ๋น ๋ฐ์ดํฐ ๋ถ์์์ ๋น์ฆ๋์ค์ ์ธ ์ธ์ฌ์ดํธ๋ฅผ ๋์ถํ๋ ๋ฑ ๋งค์ฐ ์ค์ํ ์ญํ ์ ํฉ๋๋ค.
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# Create a hash table to store the frequency of each element
freq = {}
for num in nums:
if num in freq:
freq[num] += 1
else:
freq[num] = 1
# Sort the hash table by frequency in descending order
freq = {k: v for k, v in sorted(freq.items(), key=lambda item: item[1], reverse=True)}
# Select the k elements with the highest frequency
result = []
i = 0
for num, count in freq.items():
result.append(num)
i += 1
if i == k:
break
return result
'๐ข One step' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetcode-38] Count and Say (0) | 2023.05.05 |
---|---|
[leetcode-48] Rotate Image (0) | 2023.04.30 |
[leetcode-43] Multiply Strings (0) | 2023.04.26 |
[leetcode-14] Longest Common Prefix (0) | 2023.04.24 |
[leetcode-12] Integer to Roman (0) | 2023.04.21 |