[LeetCode] 347. Top K Frequent Elements

2023. 8. 15. 23:42·Problem Solving/LeetCode

출처 : 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

 

 

방법 1)

우선순위 큐를 사용한 풀이

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freq_table = collections.Counter(nums)
        heap = []
        for i in freq_table.keys() :
            heappush(heap, (-freq_table[i], i))
        ans = []
        while k > 0 :
            k -= 1
            ans.append(heappop(heap)[1])
        return ans

 

 

방법 2)

내가 푼 방법 : Counter 활용

class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        hm = collections.defaultdict(int)
        for i in nums :
            hm[i] += 1
        lst=[]
        for k, v in collections.Counter(hm).most_common(k):
            lst.append(k)
        return lst

 

 

방법 3)

nLargest를 사용한 방법도 존재하지만 흔히 푸는 방식은 아니기에 패스.

'Problem Solving/LeetCode' 카테고리의 다른 글
  • [LeetCode] 238. Product of Array Except Self
  • [LeetCode] 36. Valid Sudoku
  • [LeetCode] 746. Min Cost Climbing Stairs
  • [LeetCode] 49. Group Anagrams
kimdozzi
kimdozzi
끝까지 포기하지 않으면, 내가 다 이겨!
  • kimdozzi
    도브로
    kimdozzi
  • 전체
    오늘
    어제
    • 분류 전체보기 (132)
      • Problem Solving (49)
        • Baekjoon (29)
        • Programmers (0)
        • LeetCode (17)
        • 삼성 유형 (2)
      • Computer Science (27)
        • Operating System (2)
        • Algorithms (13)
        • Network (6)
        • DataBase (6)
      • Backend (33)
        • JavaScript (0)
        • TypeScript (6)
        • Java (7)
        • Spring Boot (7)
        • Spring Security (6)
        • JPA (2)
        • Mybatis (1)
        • Junit5 (1)
        • Redis (3)
      • DevOps (14)
        • Git, Github (5)
        • docker (4)
        • AWS (3)
        • nginx (2)
      • etc (6)
        • IntelliJ (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 티스토리
    • 설정
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    티스토리챌린지
    누적합
    Bucket
    알고리즘
    imos법
    인덱스 시그니처
    점 업데이트
    인덱서블 타입
    온라인 쿼리
    구간 업데이트
    구간합
    삼성기출
    도커
    docker image
    S3
    segment tree
    타입스크립트
    세그먼트 트리
    AWS
    오프라인 쿼리
    오블완
    파이썬
    인터페이스
    docker
    컨테이너
    PrefixSum
    interface
    백준
    TypeScript
    python
    CORS
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
kimdozzi
[LeetCode] 347. Top K Frequent Elements
상단으로

티스토리툴바