[Python] leetcode-347. Top K Frequent Elements(정렬, 딕셔너리, lamba)

hannah·2024년 6월 29일
0

algorithm

목록 보기
6/11
post-thumbnail

문제 설명

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.


제한 사항

  • 1 <= nums.length <= 105
    -104 <= nums[i] <= 104
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

입출력 예제

numskreturn
[1,1,1,2,2,3]2[1,2]
[1]1[1]

딕셔너리의 value 빈도수에 따라 정렬한 후, 요구하는 수(k)만큼 key를 추출하면 되는 비교적 쉬운 문제이다.

신경써야 할 곳은 크게 두군데이다.

1. dict에서 특정 키가 존재하는지 확인하기

in 키워드를 사용하거나 .get() 메서드를 사용하면 된다.
이 로직에선 존재하는 지 여부를 확인하는 것이므로 in을 사용했다.

2. lambda를 사용해서 딕셔너리 정렬하기(두번째 코드 기준 설명)

원본을 수정하지 않고 새로운 정렬 리스트를 반환하는 sorted 함수를 사용하여 dict의 키들만 리스트로 가져오고, 그 리스트를 lambda 함수를 활용하여 dict의 특정 키에 해당하는 값 dict[x]을 기준으로 내림차순으로 정렬한다.

코드 작성

첫번째 코드

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dict={}
        for num in nums:
            if num in dict:
                dict[num]+=1
            else:
                dict[num]=1
        sorted_list=[]
        # 각 반복문에서 items의 두번째 요소인 value를 기준으로 내림차순 정렬
        for key,value in sorted(dict.items(), key=lambda x:-x[1]):
            sorted_list.append(key)
        return sorted_list[:k]

결과

두번째 코드

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        dict={}
        for num in nums:
            if num in dict:
                dict[num]+=1
            else:
                dict[num]=1
        # 딕셔너리의 key를 추출하여 dict[x], 즉 value로 내림차순 정렬
        sorted_list=sorted(dict.keys(), key=lambda x:-dict[x])
        
        return sorted_list[:k]

결과

오랜만에 dictionary를 활용한 문제를 풀었는데 이전에는 머리가 지끈지끈했는데 이제는 좀더 친숙해진 느낌이다!
lambda,,,혼자서 능숙하게 잘 쓰도록 더 연습해야지..

0개의 댓글