https://leetcode.com/problems/contains-duplicate/description/
LeetCode - The World's Leading Online Programming Learning Platform
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
중복을 찾는 문제의 경우 set을 애용하는 편이다.
HashSet 이용
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num: nums) {
int size = set.size();
set.add(num);
if (size == set.size()) {
return true;
}
}
return false;
}
}
HashSet 다른 풀이
다른 사람들 풀이를 보다가 add가 boolean 타입을 리턴한다는 사실을 알게 되었다.
위의 방법을 이용해서 풀었을 때 위의 풀이보다 3ms 정도 단축되었다.
class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num: nums) {
if (!set.add(num)) {
return true;
}
}
return false;
}
}
정렬 이용
class Solution {
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for(int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
}
}
'코딩테스트' 카테고리의 다른 글
136. Single Number (1) | 2024.02.07 |
---|---|
876. Middle of the Linked List (0) | 2024.02.05 |
206. Reverse Linked List (0) | 2024.02.04 |
141. Linked List Cycle (0) | 2024.01.29 |
21. Merge Two Sorted Lists (0) | 2024.01.29 |