항해99 2주차 - 상위K빈도요소
Today I learned
2022/01/19
회고록
1/19
항해 99, 알고리즘 1주차
교재 : 파이썬 알고리즘 인터뷰
10장 해시테이블
1. 이론
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. 총평
해시 테이블 훈련
Author And Source
이 문제에 관하여(항해99 2주차 - 상위K빈도요소), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@jsw4215/항해99-2주차-상위K빈도요소저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)