이거 못풀었음
막연한 생각은 했는데 코드로 옮기질 못했음
import java.util.HashMap;
import java.util.Map;
public class Mode {
public int solution(int[] array) {
int solution = 0;
// 최빈값은 주어진 값 중에서 가장 자주 나오는 값
// 맵 만듬
Map<Integer, Integer> map = new HashMap<>();
// 여기에서 Map에 Key - Value 형태로 값을 넣는데, Value를 카운트할거임
for(int i=0; i<array.length; i++) {
if(map.containsKey(array[i])) {
map.put(array[i], map.get(array[i]) + 1);
} else {
map.put(array[i], 1);
}
}
int max = 0;
// 최빈값 찾기, value중에 가장 큰 값
for(int key : map.keySet()) { // keyset()을 통해 map에서 key를 뽑아 이에 대해 향상된 for문을 돌림
int count = map.get(key); // key값에 맞는 value를 가져옴
if(count > max) { // max보다 count가 더 크다면
max = count; // max에 count를 넣음
solution = key;
} else if(count == max) { // count와 max가 같다면, solution에 -1을 넣음
solution = -1;
}
}
System.out.println("solution : " + solution);
return solution;
}
}
stream을 돌려서 푼 어마어마한 사람의 코드
참고용으로 볼게요
세상에나
class Solution {
public int solution(int[] array) {
List<Map.Entry<Integer, List<Integer>>> list = new ArrayList<>(Arrays.stream(array)
.boxed()
.collect(Collectors.groupingBy(o -> o))
.entrySet())
.stream()
.sorted((t0, t1) -> Integer.compare(t1.getValue().size(), t0.getValue().size()))
.collect(Collectors.toList());
return list.size() > 1 && list.get(0).getValue().size() - list.get(1).getValue().size() == 0 ? -1 : list.get(0).getKey();
}
}
'코딩테스트' 카테고리의 다른 글
| 피자 나눠먹기 1 (0) | 2026.03.30 |
|---|---|
| 짝수는 시러용 (0) | 2026.03.27 |
| 버블정렬 이중for문 로직 + 중앙값 구하기 (0) | 2026.03.24 |
| 유클리드 호제법에 대해서 (0) | 2026.03.23 |
| 타겟 넘버 (1) | 2025.07.20 |