IT/알고리즘
set에서 add()의 리턴값을 bool로 사용하기 (LeetCode 219)
thesse
2023. 8. 29. 14:24
300x250
반응형
https://leetcode.com/problems/contains-duplicate-ii/description/
내가 풀었던 솔루션은 아래와 같다.
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(k==0) return false;
HashSet<Integer> set = new HashSet<>();
for(int i=0; i<nums.length; i++){
if(set.contains(nums[i])) return true;
if(i>=k) set.remove(nums[i-k]);
set.add(nums[i]);
}
return false;
}
}
런타임 비트가 애매하게 80퍼대가 나오길래 다른사람의 솔루션을 봤더니
나와 거의 비슷한데 한 줄을 다르게 쓰고 있었다.
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(k==0) return false;
HashSet<Integer> set = new HashSet<>();
for(int i=0; i<nums.length; i++){
if(!set.add(nums[i])) return true; // 여기
if(i>=k) set.remove(nums[i-k]);
}
return false;
}
}
set.add()를 할 경우 set에 값이 추가될 뿐만 아니라
추가할 값이 set에 존재하지 않아 새로 추가하는거면 true, 이미 존재하고 있던 값을 업데이트 하는거면 false를 리턴한다고 한다.
나는 우선 nums[i]가 set에존재하는지 확인 후 add를 했는데
그렇게 하지 않고 if 조건 안에서 add를 했더니 시간이 좀 더 단축되었다.
300x250
반응형