https://leetcode.com/problems/top-k-frequent-elements/
Top K Frequent Elements - LeetCode
Can you solve this real interview question? 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. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
leetcode.com
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
๋ด๊ฐ ํผ ๊ฒ :
์ด๋ฒ์๋ ๋์ ๋๋ฆฌ ์ฌ์ฉํด์ key ์ ์์๋ฅผ ๋ฃ๊ณ ๋ฐ๋ณต๋ ๋๋ง๋ค +1 ์ ํด์ฃผ์๋ค.
๊ทธ๋ฆฌ๊ณ sorted๋ฅผ ํด์ฃผ๋๋ฐ value ๊ธฐ์ค์ผ๋ก ํ๋ ๋ฐฉ๋ฒ์ด ํ์ด์ฌ์์๋ ์ง์ํด์ค๊ฒ ๊ฐ์ ๋๋์ด ๋ค์ด์
์ฐพ์๋ณด๋ค๊ฐ ์ด์ํ๊ฑธ ์ฐพ์์ ์ ์ํด๋ดค๋ค.
lambda x: x[1] ์ key ์ธ์๋ก ์ฌ์ฉ๋๋ ๋๋ค ํจ์๋ก ์นด-๊ฐ ์์์ ๊ฐ์ ์ถ์ถํด์ ์ ๋ ฌ์ ๊ธฐ์ค์ผ๋ก ์ฌ์ฉํ๋ค.
x[1] ์ ํํ์ ๋ ๋ฒ์งธ ์์์ธ value ๋ฅผ ๋ํ๋ธ๋ค. ์ ๋ ฌ์ ํค๋ก ์ฌ์ฉํ๋ค. ์๋์์ ๋ ์์ธํ ์ค๋ช ํ๋ค
class Solution(object):
def topKFrequent(self, nums, k):
resultDic = {}
for num in nums:
if num in resultDic:
resultDic[num]+=1
else:
resultDic[num] = 1
sorted_itmes = sorted(resultDic.items(),key=lambda x:x[1],reverse=True)
topK = sorted_itmes[:k]
return [item[0] for item in topK]
lambda ์ฌ์ฉ ์์ ๋ฅผ ๋ช๊ฐ ๋ง๋ค์ด๋ณด๋ฉด
์ต๋ช ํจ์๋ฅผ ์์ฑํ๋๋ฐ ์ฌ์ฉ๋๋ ํค์๋์ธ๋ฐ. ๊ตฌ์กฐ์ ์์
lambda arguments: expression
1. ๊ฐ๋จํ ์ฐ์ฐ
add = lambda x, y : x+y
result = add(3,5)
๊ฒฐ๊ณผ : 8
2. ์ ๋ ฌ์ ํค๋ก ์ฌ์ฉ
data = [(1,5), (3,2), (2,8)]
sorted(data, key=lambda x: x[1])
๊ฒฐ๊ณผ : [(3,2),(1,5),(2,8)]
3. ๋งต ํจ์์ ํจ๊ป ์ฌ์ฉ
numbers = [1,2,3,4,5]
list(map(lambda x:x **2,numbers))
๊ฒฐ๊ณผ : [1,4,9,16,25]
4. ํํฐ ํจ์์ ํจ๊ป ์ฌ์ฉ
numbers = [1,2,3,4,5,6,7,8,9]
list(filter(lambda x: x %2==0,numbers)
๊ฒฐ๊ณผ : [2,4,6,8]
'์๊ณ ๋ฆฌ์ฆ > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
49. Group Anagrams (0) | 2023.08.18 |
---|---|
1. Two Sum (0) | 2023.08.16 |
242. Valid Anagram (0) | 2023.08.13 |
217. Contains Duplicate (0) | 2023.08.10 |