728x90

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์„ ์ด์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  1. hash table
  • ์ •์ˆ˜ ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉฐ ์›์†Œ์˜ ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ์ €์žฅํ•˜๋Š” hash table์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
  • ์ ‘๊ทผ ํšŸ์ˆ˜๊ฐ€ ๋งŽ์€ ์ƒ์œ„ K๊ฐœ์˜ ์›์†Œ๋ฅผ ์ €์žฅํ•  ๊ฒฐ๊ณผ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
  • hash table์—์„œ ๊ฐ€์žฅ ๋“ฑ์žฅํ•œ ํšŸ์ˆ˜๊ฐ€ ํฐ ์›์†Œ๋ถ€ํ„ฐ K๊ฐœ ๊นŒ์ง€๋งŒ ๊ฒฐ๊ณผ ๋ฐฐ์—ด์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
  1. 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
๋‹คํ–ˆ๋‹ค