์• ์ •์ฝ”๋”ฉ ๐Ÿ’ป

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