프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
의식의 흐름
크기가 제일 많은 것부터 k개될 때까지 담으면 될 것 같은데
풀이
1. HashMap을 이용해 key로는 크기를, value로는 개수를 갖는 map 생성한다.
2. 생성한 map을 이용해 size(크기)와 cnt(개수)를 갖는 Tangerine 클래스를 담는 ArrayList 생성한다.
3. 생성한 ArrayList를 정렬한다.
=> cnt를 기준으로 내림차순 정렬됨
4. 정렬한 ArrayList를 이용해 cnt가 가장 높은 것부터 차례대로 담는다. 이때, 담은 총 개수가 k보다 크거나 같으면 break.
코드
import java.util.*;
class Tangerine implements Comparable<Tangerine>{
int size; // 크기
int cnt; // 개수
public Tangerine(int size, int cnt){
this.size = size;
this.cnt = cnt;
}
@Override
public int compareTo(Tangerine o) { // cnt에 대해 내림차순 정렬
return o.cnt - this.cnt;
}
}
class Solution {
public int solution(int k, int[] tangerine) {
int answer = 0;
HashMap<Integer, Integer> map = new HashMap<>();
ArrayList<Tangerine> tangerines = new ArrayList<>();
for(int i=0;i<tangerine.length;i++){
if(map.containsKey(tangerine[i])){
map.put(tangerine[i],map.get(tangerine[i])+1);
}
else{
map.put(tangerine[i],1);
}
}
for(Integer key:map.keySet()){
tangerines.add(new Tangerine(key, map.get(key)));
}
Collections.sort(tangerines);
int total = 0;
for(Tangerine tan:tangerines){
if(total>=k)
break;
total += tan.cnt;
answer++;
}
return answer;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[JAVA] 프로그래머스 - 거스름돈 (0) | 2023.11.23 |
---|---|
[JAVA] 프로그래머스 - [3차]압축 (0) | 2023.05.03 |
[JAVA] 프로그래머스 - 튜플 (0) | 2023.05.01 |
[JAVA] 프로그래머스 - [1차] 캐시 (0) | 2023.05.01 |