https://leetcode.com/problems/contains-duplicate/description/

 

Contains Duplicate - LeetCode

Can you solve this real interview question? 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 Ex

leetcode.com

 

주어진 배열에 중복된 값이 있는지 체크하는 문제이다.
중복과 관련해서 가장 쉽게 사용할 수 있는 자료구조는 Set 이다.
Set은 중복된 값을 넣을 경우 제거되고 하나의 값으로 저장되기 때문이다.
배열의 값을 순차적으로 넣으며 Set의 크기가 변하는지 확인하여 해결해주었다.

import java.util.*;  
  
public class Solution {  
    public boolean containsDuplicate(int[] nums) {  
        Set<Integer> set = new HashSet<>();  
        int size = 0;  
        for(int i = 0; i < nums.length; i++){  
            size++;  
            set.add(nums[i]);  
            if(size != set.size()) return true;  
        }  
  
        return false;  
    }  
}

'Algolithm-Leetcode > Arrays & Hashing' 카테고리의 다른 글

Top K Frequent Elements  (0) 2026.08.23
Group Anagrams  (0) 2026.08.20
Valid Anagram  (0) 2026.08.07
Two Sum  (0) 2026.07.21

+ Recent posts