[LeetCode] contains Duplicate

CodingTest|2025. 11. 19. 23:28

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

 

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

Explanation:

The element 1 occurs at the indices 0 and 3.

 

Example 2:

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

Output: false

Explanation:

All elements are distinct.

 

Example 3:

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

Output: true

 

Constraints:

  • 1 <= nums.length <= 105
  • -10^9 <= nums[i] <= 10^9

Unlike JavaScript, if you don’t use Java regularly, you start forgetting bits and pieces…

So I decided to practice with Java from now on and picked an easy problem.

자바스크립트랑 다르게 자바는 안 써버릇 하면 조금씩 잊어버린다...

그래서 지금부터는 자바로 풀어보려고 일단 쉬운 문제 하나 잡아봄.

 

The task is simple: given an array, return true if there are duplicate numbers, otherwise false.

간단하게 주어진 배열 내에 중복된 숫자가 있으면 true, 아니면 false를 리턴하는 문제.

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> counts = new HashSet<>();
        for(int num:nums){
            if(counts.contains(num)){
                return true;
            }
            counts.add(num);
        }

        return false;
    }
}

 

I created a set and added numbers to it one by one. If a number is already in the set, it returns true.

셋을 하나 만들고 그 안에 숫자를 넣으면서, 이미 동일한 숫자가 안에 들어 있으면 true를 반환하도록 했다~_~

'CodingTest' 카테고리의 다른 글

[LeetCode] Top K Frequent Elements  (0) 2025.11.21
[LeetCode] Guess Number Higher or Lower  (0) 2025.07.17
[LeetCode] Edit Distance  (0) 2025.07.09