Algorithm/알고리즘 문제풀이
LeetCode 217(Contains Duplicate, java)
devraphy
2022. 4. 11. 15:04
0. 문제
https://leetcode.com/problems/contains-duplicate/
Contains Duplicate - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
1. 문제 설명
- 이 문제의 핵심은 배열 요소의 중복 유무를 검사하는 것이다.
- 배열 요소의 중복 검사를 위해서는 for문을 이용해 배열의 요소를 HashSet에 삽입한다.
- HashSet.add() 메서드는 boolean을 반환하기 때문에, 해당 메서드가 false를 반환하면 중복 값이 존재하는 것이다.
- 중복 값이 존재하면 true, 없다면 false를 반환한다.
2. 정답 코드
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for(int num : nums) {
if(!set.add(num)) { // add()에서 false를 반환하는 경우 == 중복 값 발생
return true;
}
set.add(num);
}
return false;
}
}