CodeWars 마흔 네 번째 문제
Updated:
Delete occurrences of an element if it occurs more than n times
public static int[] deleteNth(int[] elements, int maxOccurrences) {
if(maxOccurrences < 1) {
return new int[] {};
}
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
List<Integer> deleteNthList = new ArrayList<Integer>();
for(int number : elements) {
Integer mapNum = map.put(number, map.getOrDefault(number, 0) + 1);
if(mapNum == null || mapNum < maxOccurrences) {
deleteNthList.add(number);
}
}
return deleteNthList.stream().mapToInt(i->i).toArray();
}
- Best 코드와 알고리즘은 같았다.
- 그러나 클린 코드를 위해 유용한 새로운 메소드 두 개를 배웠다.
- 하는 map에서 사용하는 getOrDefault이고 다른 하나는 list를 배열로 변경해주는 stream이다.
- getOrDefault는 첫번째 인자값이 없으면 두번째 인자로 return해주는 것이다.
- stream.().mapToInt(i->i).toArray()는 리스트를 배열로 변환