서하아빠의 개발 블로그

217. Contains Duplicate 본문

알고리즘/LeetCode

217. Contains Duplicate

서하아빠 2022. 5. 20. 17:39

Easy

문제링크

 

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

 

Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

 

[풀이] 

배열 nums에 중복된 숫자가 최소 2번 이상 나오는지 체크.

중복된 숫자가 없다면 true, 중복된 숫자가 하나라도 있다면 false

 

중복을 허용하지 않는 HashSet 자료구조를 활용해서 중복체크

 

1. 배열의 길이 만큼 반복문을 수행한다.

   1) Hashset에 값이 있을 경우에는 true를 반환한다.

   2) Hashset에 값이 없을 경우에는 Hashset에 해당 값을 add한다.

2. 반복문 수행이 완료되었을 경우에는 중복된 값이 하나도 없다는 것을 의미함.

   이때는 false를 반환한다.

class Solution {
    public boolean containsDuplicate(int[] nums) {
        int len = nums.length;
        HashSet<Integer> set = new HashSet<>();
        
        for(int i=0; i < len; i++) {
            if(set.contains(nums[i])) {
                return true;
            } else {
                set.add(nums[i]);
            }    
        }
        return false;
    }
}

 

 

 

'알고리즘 > LeetCode' 카테고리의 다른 글

20. Valid Parentheses  (0) 2022.05.24
121. Best Time to Buy and Sell Stock  (0) 2022.05.20
25. Reverse Nodes in k-Group  (0) 2022.05.20
61. Rotate List  (0) 2022.05.19
200. Number of Islands  (0) 2021.06.14