Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- RxJS 결합 오퍼레이터
- RxJS 에러 처리
- 개발자커뮤니케이션
- Observable vs Array
- leetcode
- React hooks 남용 사례
- 알고리즘
- RxJS 함수형 프로그래밍
- React 리렌더링 최적화
- useMemo 성능 최적화
- React useCallback 사용법
- 스쿼드조직
- RxJS 마블 다이어그램
- RxJS 생성 오퍼레이터
- React 성능 최적화 방법
- 달래스터디
- DaleStudy
- RxJS 변환 오퍼레이터
- useCallback 성능 최적화
- Climbing Stairs
- React useMemo 사용법
- 협업문화
- leedcode
- 자바스크립트 고차 함수 vs Observable
- RxJS 멀티캐스팅
- React useEffect 안티패턴
- contains duplicate
- Blind75
- RxJS 오퍼레이터
- 알고리즘스터디
Archives
- Today
- Total
수쿵의 IT월드
DaleStudy | Leetcode Study 1주차 - Top K Frequent Elements 본문

문제
Given an integer array nunmsand an integer k, return the kmost frequest 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 <= 10^5
- -10^4 <= nums[i] <= 10^4
kis in the range[1, the number of unique elements in the array].- It is guaranteed that the answer in unique.
Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
풀이
이 문제는 배열에서 가장 빈번하게 나오는 숫자 k개 골라 배열로 리턴하는 문제이다. 일단 나는 알고리즘 문제를 접할 때, 가장 빈번하게든지 등의 정보를 저장해야하는 일이 있다면, 객체를 저장하는 것을 생각하는 편이다. 그리고 단계를 나눠서 생각하는 것이 중요하다.
- 먼저 Map을 이용해서 원소의 갯수가 몇 개인지 저장한다.
- 그 정보를 기반으로 가장 빈번하게 나온 순서대로 정렬을 시킨다.
- 마지막으로 k만큼 자른 뒤에 그 키 값을 리턴하면 끝난다.
function topKFrequent(nums: number[], k: number): number[] {
const frequentMap = new Map<number, number>();
for (const num of nums) {
frequentMap.set(num, (frequentMap.get(num) ?? 0) + 1);
}
const sorted = Array.from(frequentMap.entries())
.sort((a, b) => b[1] - a[1]);
return sorted.slice(0, k).map(([key]) => Number(key))
};
이렇게 풀면 O(n)의 시간복잡도와 O(n)의 공간복잡도를 가지게 된다.
Link: https://leetcode.com/problems/top-k-frequent-elements/description/