Home leetcode 풀이 - Contains Duplicate
Post
Cancel

leetcode 풀이 - Contains Duplicate

문제

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


내 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public boolean containsDuplicate(int[] nums) {
        // 풀이법: 중복을 허용하지 않는 HashSet 의 특성을 사용해, 배열을 HashSet에 복사후 크기를 비교한다. 
        //using HashSet's charcteristic (unable to save duplicated values)
        HashSet<Integer> removeDuplicate = new HashSet<>();
        for(int i=0; i<nums.length; i++){
            removeDuplicate.add(nums[i]);
        }
        
        // 둘이 크기가 다르다면 중복 값 있는것이기에 return true
        //if two objects have different size, it means the array has duplicated values. Return true. 
        if(removeDuplicate.size() != nums.length){
            return true;
        }
        
        return false; 
    }
}
This post is licensed under CC BY 4.0 by the author.