Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
정수형 배열이 주어지면, 배열에 중복된 항목이 있는지 찾아라.
배열에 값이 두 번 이상 나타나면 함수가 true를 반환해야 하고,
모든 항목이 중복되지 않으면 false를 반환해야 한다.
풀이 방법
중복 되지 않는 값을 저장하는 Set을 이용하여 풀이하기!
1. 배열의 길이만큼 반복문을 수행하며, HashSet에 값이 존재할 경우 true를 반환한다.
2. HashSet에 값이 없을 경우, 해당 값을 add 한다.
3. 반복문 수행이 끝났을 경우(중복되는 값이 하나도 없을 경우), false를 반환한다.
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for(int i=0; i<nums.length; i++) {
if(set.contains(nums[i]))
return true;
else
set.add(nums[i]);
}
return false;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[JAVA] LeetCode 21 - Merge Two Sorted Lists (0) | 2020.11.23 |
---|---|
[JAVA] LeetCode 122 - Best Time to Buy and Sell Stock II (0) | 2020.11.22 |
[JAVA] LeetCode 171 - Excel Sheet Column Number (0) | 2020.11.22 |
[JAVA] LeetCode 108 - Convert Sorted Array to Binary Search Tree (0) | 2020.11.16 |
[JAVA] LeetCode 206 - Reverse Linked List (0) | 2020.11.16 |