문제 자체는 금방 풀었지만, map과 stream collector 등 다른사람의 풀이방법에도 배울 점이 많아 공유하고, 간단히 코드를 분석해보았다.
1. 본인 풀이
sort를 통해 최빈값을 구한다.
마지막에서 두번째 값이 최빈값과 같으면 최소 2개 이상의 같은 최빈값이 존재하므로, -1리턴한다.
아니라면, 최빈값이 하나이므로 최빈값과 같은 수를 만나면 바로 해당 값의 index를 반환한다.
import java.util.Arrays;
class Solution {
public int solution(int[] array) {
int answer = 0;
int []count = new int[1000];
for(int i = 0; i<array.length; i++){
count[array[i]]++;
}
int []compare = count.clone();
Arrays.sort(compare);
int max = compare[compare.length-1];
if(max == compare[compare.length - 2]) return -1;
for(int i = 0; i<count.length; i++){
if(max == count[i]) return i;
}
return answer;
}
}
참고 풀이 1
Map을 이용해 풀었다. 나는 map함수는 잘은 모르는데 이렇게 풀면 한 번의 loop로도 풀어낼 수 있어서 시간복잡도 면에서 좋은 것 같다. java의 map 함수를 공부해야겠다.
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;
}
}
참고 풀이 2
collect : strim을 원하는 결과 형태로 수집하는데 사용.
Collectors : 원하는 내부 함수를 사용하기 위함. 객체 선언 따로 없이 사용
groupingBy : 공식 문서 참고 Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.
entrySet : Map에서 모든 Entry(Key-Value쌍)를 가져와 Set 객체로 반환한다. forEach loop를 사용해 각 Entry에 순차적으로 접근 가능
관련 공식 문서 : https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
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();
}
}
'코딩테스트 > Programmers' 카테고리의 다른 글
[프로그래머스] 저주의 숫자 3 (0) | 2025.01.31 |
---|---|
[프로그래머스] 특이한 정렬 (1) | 2025.01.30 |
[프로그래머스] PCCE 기출문제 10번 / 데이터 분석 (0) | 2025.01.26 |
[프로그래머스] PCCE 기출문제 10번 / 공원 (0) | 2025.01.26 |
[프로그래머스] 등차수열의 합 (0) | 2025.01.23 |