문제
내가 작성한 정답
import java.util.*;
class Solution {
public int solution(int[] array) {
Map<Integer,Integer> map = new HashMap<>();
int max = 0;
int fre = -1;
boolean only = false;
for(int a: array){
int count = map.getOrDefault(a,0)+1;
map.put(a,count);
if(count > max){
max = count;
fre = a;
only = true;
}else if(count == max) {
only = false;
}
}
return only? fre: -1;
}
}
다른 사람들의 정답
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Arrays;
class Solution {
public int solution(int[] array) {
// 1. 주어진 배열을 List<Map.Entry<Integer, List<Integer>>> 형태로 변환
List<Map.Entry<Integer, List<Integer>>> list = new ArrayList<>(
// 2. 배열을 스트림으로 변환 후, 박싱하여 Integer 객체로 변환
Arrays.stream(array)
.boxed()
// 3. 같은 값들을 그룹화하여 Map<Integer, List<Integer>> 형태로 변환
.collect(Collectors.groupingBy(o -> o))
// 4. Map의 엔트리 세트를 가져옴
.entrySet()
).stream()
// 5. 출현 횟수가 많은 순서로 정렬
.sorted((t0, t1) -> Integer.compare(t1.getValue().size(), t0.getValue().size()))
// 6. 정렬된 결과를 리스트로 수집
.collect(Collectors.toList());
// 7. 최빈값이 여러 개인지 확인
// list의 크기가 1보다 크고, 첫 번째와 두 번째의 출현 횟수가 같으면 -1 반환
return list.size() > 1 && list.get(0).getValue().size() - list.get(1).getValue().size() == 0 ? -1 : list.get(0).getKey();
}
}

Share article