Celenort
Conciencia
게시물 253
오늘 0
전체 0
A site about logging consciousness

[LeetCode] Contains Duplicate

Contains Duplicate

Category: Array

Deadline: 1st week (12/31 - 1/7)

Difficulty: Easy

Github: https://github.com/iamseokhyun/2022-algorithm-study/tree/master/array/ContainsDuplicate/

LeetCode link: https://leetcode.com/problems/contains-duplicate/

Problem

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 <= 10^5
  • -10^9 <= nums[i] <= 10^9

Solution

public class Solution
{
    public bool ContainsDuplicate(int[] nums)
    {
        nums = Divide(nums);

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

        return false;
    }

    public int[] Divide(int[] nums)
    {
        if (nums.Length < 2)
        {
            return nums;
        }

        int pivot = (int)(nums.Length / 2);
        int[] leftarray = nums[0..pivot];
        int[] rightarray = nums[pivot..(nums.Length)];

        leftarray = Divide(leftarray);
        rightarray = Divide(rightarray);

        return Merge(leftarray, rightarray);
    }

    public int[] Merge(int[] leftarray, int[] rightarray)
    {
        int l = leftarray.Length - 1;
        int r = rightarray.Length - 1;
        int[] temp = new int[leftarray.Length + rightarray.Length];

        while (l >= 0 && r >= 0)
        {
            if (leftarray[l] > rightarray[r])
            {
                temp[l + r + 1] = leftarray[l];
                l--;
            }
            else
            {
                temp[l + r + 1] = rightarray[r];
                r--;
            }
        }

        while (l >= 0)
        {
            temp[l] = leftarray[l];
            l--;
        }

        while (r >= 0)
        {
            temp[r] = rightarray[r];
            r--;
        }

        return temp;
    }
}

Comment

  • Idea : 내림차순 정렬 후, 0~Length-1 까지 Search하여, 인접한 index끼리 같은 값이 있는지를 확인. 있으면 true, 끝까지 찾아봤음에도 없으면 false 출력.
댓글을 불러오는 중입니다.