반응형
문제 설명
최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
제한사항
- 0 < array의 길이 < 100
- 0 ≤ array의 원소 < 1000
import java.util.*;
class Solution {
public int solution(int[] array) {
HashMap<Integer, Integer> hashMap = new HashMap<>();
for (int n : array) hashMap.put(n, hashMap.getOrDefault(n, 0) + 1);
int max = Collections.max(hashMap.values());
int cnt = 0;
int result = 0;
for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()) {
if (entry.getValue() == max) {
cnt++;
result = entry.getKey();
}
}
return cnt == 1 ? result : -1;
}
}
1. getOrDefault(Object key, V DefaultValue)
- key : 값을 가녀와야 하는 요소의 키.
- defaultValue : 지정된 키로 매핑된 값이 없는 경우 반환되어야 하는 기본값.
반환값 : 찾는 key가 존재하면 해당 key에 매핑되어 있는 값을 반환하고, 그렇지 않으면 디폴트 값이 반환된다.
2. Collections.max()
: 컬렉션의 최대 요소를 반환
3. hashMap.values()
: 해당 map의 value 목록을 Collection 형태로 리턴한다.
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class HashMapPrint {
public static void main(String[] args) {
// HashMap 준비
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Orange");
// map.values()
Collection<String> values = map.values();
System.out.println(values); // [Apple, Banana, Orange]
}
}
4. hashMap.entrySet()
: 해당 map의 key와 value를 가지는 Set 객체를 리턴한다.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapPrint{
public static void main(String[] args){
// hashMap 준비
Map<Integer, String> map = new HashMap<Integer,String>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Orange");
// for loop (entrySet())
for(Entry<Integer, String> entrySet : map.entrySet()){
System.out.println(entrySet.getKey() + " : " + entrySet.getVaule());
}
}
}
map.entrySet() 메소드를 호출하여 map의 key와 value를 포함하는 Entry 객체의 Set을 얻어왔다.
그리고, 이 Set 객체를 순회하며 map의 key, value를 출력하였다.
반응형
'알고리즘 > Programmers' 카테고리의 다른 글
[프로그래머스] 중앙값 구하기(java) (0) | 2023.01.02 |
---|