항해99 2주차 - 상위K빈도요소

Jang Seok Woo·2022년 1월 23일
0

알고리즘

목록 보기
23/74

Today I learned
2022/01/19

회고록


1/19

항해 99, 알고리즘 1주차

교재 : 파이썬 알고리즘 인터뷰

10장 해시테이블

1. 이론

https://velog.io/@jsw4215/%ED%95%AD%ED%95%B499-2%EC%A3%BC%EC%B0%A8-%EB%B3%B4%EC%84%9D%EA%B3%BC-%EB%8F%8C

2. 문제

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/

3. MySol


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))
    

4. 배운 점

  • 해시 테이블을 이용하면 그리 어렵지 않은 문제이다.

5. 총평

해시 테이블 훈련

profile
https://github.com/jsw4215

0개의 댓글