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 |
Tags
- 출처 문어박사
- 스프링부트팔로우취소
- 출처 노마드코더
- 스프링이미지업로드
- 멀티폼
- vm도커설치하는법
- 파이썬sort
- 서버에도커설치
- 스프링부트사진올리기
- centos도커설치
- 스프링구독
- 스프링부트api
- 스프링부트서버에사진전송
- 스프링사진
- 출처 따배도
- WAS웹서버
- 스프링부트
- dockerinstall
- 스프링익셉션처리
- 스프링사진업로드
- ssh도커설치
- 출처 코딩셰프
- 우분투도커설치
- springboot_exception_handler
- 출처 메타코딩
- 인스타클론
- 도커설치하는법
- 스프링부트구독취소
- 스프링부트팔로잉
- 스프링부트중복예외처리
Archives
- Today
- Total
MakerHyeon
347. Top K Frequent Elements 본문
https://leetcode.com/problems/top-k-frequent-elements/
Top K Frequent Elements - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
! 시간 복잡도는 O(nlogn) 이하여야 함
SOLUTION CODE
# PYTHON
● Count 를 이용한 풀이
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# Counter({1: 3, 2: 2, 3: 1})
c=Counter(nums)
# count숫자 가져오기
res = c.most_common(k)
return [num[0] for num in res]
# cf_simple ver
def topKFrequent(nums, k):
return [x[0] for x in Counter(nums).most_common(k)]
● Bucket sort
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
freq = [[] for i in range(len(nums) + 1)]
for n in nums: # count[원소] = frequent
count[n] = 1 + count.get(n,0)
for n, c in count.items(): # bucket sort
freq[c].append(n)
res = []
for i in range(len(freq) - 1, 0, -1): # 배열끝부터 앞으로 검사
for n in freq[i]:
res.append(n)
if len(res) == k:
return res
# C++
class Solution {
public:
static bool comp(const pair<int,int> &a, const pair <int,int> &b){
return (a.second>b.second);
}
vector<int> topKFrequent(vector<int>& nums, int k) {
vector<int> res; // 정답
map<int,int> count_em; // count_em[원소] = 카운트
for(int i=0; i<nums.size(); i++)
count_em[nums[i]]++; // 해당 key값에 value증가
//map ->vector에 복사
vector<pair<int,int>> v(count_em.begin(),count_em.end());
sort(v.begin(),v.end(),comp);
for(int i=0;i<k;i++) res.push_back(v[i].first);
return res;
}
};
● Count 의 시간 복잡도는 O(N)
● Bucket sort
- input array size가 한정되어있을때 주로 사용하며,시간복잡도는 O(N)
- Bucket array size = input array size
ex)[1, 1, 1, 2, 2, 100]
i(count) | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
values | [100] | [2] | [1] |
● Map / vector 차이를 정리해보았다.
#include <map>
#include <vector>
using namespace std;
int main(){
map<string,int> m;
vector<int> v;
//요소 추가 ***
//m
m.insert(make_pair("key",1));
m["key2"] = 2;
//v
v.push_back(1);
vector <string> v2 {"vector","practice"};
//map->vector copy ***
// 선언 뒤 복사
vector<pair<string,int> vector_c(m.size())>;
copy(m.begin(), m.end(), vector_c.begin());
// 선언 + 복사
vector<pair<string,int>vector_c1(m.begin(),m.end())>;
//map->map copy
map<string,int> mapTarget;
if(0<m.size()){
std::copy(m.begin(),m.end(), std::inserter(mapTarget,maTarget.begin()));
}
}
● compare
-"왼쪽이 오른쪽보다" 가 기준임
bool compare(int a,int b){ return a>b } //내림차순 정렬
'Algorithm > LeetCode' 카테고리의 다른 글
682. Baseball Game (0) | 2023.01.02 |
---|---|
1929. Concatenation of Array (0) | 2023.01.01 |
1. Two Sum (0) | 2022.12.22 |
26. Remove Duplicates from Sorted Array (0) | 2022.12.21 |
242. Valid Anagram (1) | 2022.12.20 |
Comments