📌 문제 링크 :
https://leetcode.com/problems/unique-number-of-occurrences
✅ 내 풀이(Success) :
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
for (int key : arr) {
map.put(key, map.getOrDefault(key, 0) + 1);
}
Set<Integer> set = new HashSet<>(map.values());
return map.size() == set.size();
}
}
🧐 리뷰 :
문제의 해결법은 꽤 간단하다. 해시맵에 값이 중복되는 값이 없으면 true, 중복이 있다면 false를 반환하면 된다. 이 중복여부를 체크하는 것은 해시셋과 해시맵의 길이는 비교하면 된다. 길이가 같다면 중복된 값이 없다는 의미이고, 길이가 같지 않다면 중복값이 존재하여 해시셋에서 의해 중복되는 값이 제거되어 길이가 달라졌다는 것을 의미하기 때문이다.
파이썬으로 알고리즘 문제를 풀때는 딕셔너리(자바의 해시맵)의 get(key, '초기값') 함수를 사용하거나 초기값을 기본으로 셋팅하기 위해서 defaultdict를 사용했는데, 자바에서는 이 부분은 getOrDefault(key, '초기값') 메서드로 할 수 있다.
'알고리즘 문제 풀이: 자바 > LeetCode' 카테고리의 다른 글
| 345. Reverse Vowels of a String (0) | 2025.11.04 |
|---|---|
| 151. Reverse Words in a String (0) | 2025.11.03 |
| 1732. Find the Highest Altitude (0) | 2025.11.01 |
| 2215. Find the Difference of Two Arrays (0) | 2025.10.31 |
| 643. Maximum Average Subarray I (0) | 2025.10.30 |
댓글