객체 만들어서 사용
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public int solution(int limit, int[] tangerine) {
int answer = 0;
int count = 0;
Map<Integer, Tangerine> counter = new HashMap<>();
for (int tangerineNumber : tangerine) {
Tangerine curTangerine = counter.getOrDefault(tangerineNumber, new Tangerine(tangerineNumber, 0));
curTangerine.count++;
counter.put(tangerineNumber, curTangerine);
}
List<Tangerine> tangerines = new ArrayList<>(counter.values());
tangerines.sort(null);
for (Tangerine curTangerine : tangerines) {
int tempCount = curTangerine.count;
count += tempCount;
answer++;
if (count >= limit) {
break;
}
}
return answer;
}
}
class Tangerine implements Comparable<Tangerine> {
int number;
int count;
public Tangerine(int number, int count) {
this.number = number;
this.count = count;
}
@Override
public int compareTo(Tangerine o) {
return -Integer.compare(this.count, o.count);
}
}
객체 없이 코드 작성
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public int solution(int limit, int[] tangerine) {
int answer = 0;
int count = 0;
Map<Integer, Integer> counter = new HashMap<>();
for (int tangerineNumber : tangerine) {
int curTangerine = counter.getOrDefault(tangerineNumber, 0);
curTangerine++;
counter.put(tangerineNumber, curTangerine);
}
List<Integer> tangerines = new ArrayList<>(counter.keySet());
tangerines.sort((a, b) -> counter.get(b) - counter.get(a));
for (Integer keyIdx : tangerines) {
count += counter.get(keyIdx);
answer++;
if (count >= limit) {
break;
}
}
return answer;
}
}