[LeetCode] Contains Duplicate

아르당·2025년 10월 21일

LeetCode

목록 보기
51/68
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

정수 배열 nums가 주어졌을 때, 배열에 값이 두 번 이상 나타나면 true를 반환하고, 모든 요소가 다르면 false를 반환해라.

Example

#1
Input: nums = [1, 2, 3, 1]
Output: true
Explanation:
요소 1이 0과 3번째가 중복된다.

#2
Input: nums = [1, 2, 3, 4]
Output: false
Explanation:
모든 요소가 중복되지 않는다.

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

Constraints

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

Solved

class Solution {
    public boolean containsDuplicate(int[] nums) {
        Arrays.sort(nums);

        for(int i = 1; i < nums.length; i++){
            if(nums[i] == nums[i - 1]) return true;
        }

        return false;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글