거의 알고리즘 일기장

[leetcode] - 217. Contains Duplicate 본문

알고리즘 문제풀이

[leetcode] - 217. Contains Duplicate

건우권 2023. 4. 1. 00:13

problem

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

 

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

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.

Constraints:

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

Access

1. brute force (O(n^2))

The problem has constraint (0 <= nums.length <= 10^5)

maybe run loop 10^10 on a rough estimate.

 

so, I think get a timeout error

function containsDuplicate(nums: number[]): boolean {
    for(let i = 0; i<nums.length; i++){
        const c1 = nums[i];

        for(let j = i+1; j<nums.length; j++){
            const c2 = nums[j];
            
            if(c1 === c2){
                return true;
            }
        }   
    }

    return false;
};

fortunately, The solution is passed.

 

but, the runtime score is not good. 

2. using cache O(n)

The solution needs large memory but, good runtime speed.

 

save the previous number. so, we don't need another for loop in first for loop.

function containsDuplicate(nums: number[]): boolean {
    //using cache O(n)
    const cache = new Map<number, boolean>();
    for(let i = 0; i<nums.length; i++){
        const currentNum = nums[i];
        
        //check! is there currentNum in cache
        const isThere = cache.get(currentNum);
        
        if(isThere){
            return true;
        }
        
        //set currentNum in cache
        cache.set(currentNum, true);
    }

    return false;
};

this solution has a good runtime.

but, use a lot of memory.

반응형
Comments