Today I learned
2022/01/19
회고록
항해 99, 알고리즘 1주차
교재 : 파이썬 알고리즘 인터뷰
10장 해시테이블
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]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Constraints:
1 <= nums.length <= 105
k is in the range [1, the number of unique elements in the array].
It is guaranteed that the answer is unique.
https://leetcode.com/problems/top-k-frequent-elements/
def solution(elements, k):
    hash = {}
    result = []
    for e in elements:
        if e in hash:
            hash[e]+=1
        else:
            hash[e]=1
    for i in hash:
        if hash[i]>=k:
            result.append(i)
    return result
if __name__ == '__main__':
    nums = [1,1,1,2,2,3]
    k = 2
    result = solution(nums, k)
    print('result : ' + str(result))
    
해시 테이블 훈련