문제
내가 작성한 정답
class Solution {
public int solution(int[] array) {
int f = 0, max = 0,cnt=0;
int[] arr = new int[1000];
for(int i:array) arr[i]++;
for(int i=0; i<1000; i++){
if(max<arr[i]) {f=i; max=arr[i];}
}
for(int i:arr) if(i==max) cnt++;
return cnt>1?-1:f;
}
}다른 사람들의 정답
import java.util.*;
class Solution {
public int solution(int[] array) {
int maxCount = 0;
int answer = 0;
Map<Integer, Integer> map = new HashMap<>();
for(int number : array){
int count = map.getOrDefault(number, 0) + 1;
if(count > maxCount){
maxCount = count;
answer = number;
}
else if(count == maxCount){
answer = -1;
}
map.put(number, count);
}
return answer;
}
}
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) {
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();
}
}Share article