Notice
Recent Posts
Recent Comments
Link
거의 알고리즘 일기장
[leetcode] - 217. Contains Duplicate 본문
problem
https://leetcode.com/problems/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.
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.
반응형
'알고리즘 문제풀이' 카테고리의 다른 글
[leetcode] - 121. Best Time to Buy and Sell Stock (0) | 2023.03.31 |
---|---|
[leetCode] - 1. Two Sum - (0) | 2023.03.31 |
백준 1175번 _ 배달 (2) | 2020.11.07 |
백준 1194번 _ 달이 차오른다, 가자. (0) | 2020.11.07 |
백준 5373번 _ 큐빙 (0) | 2020.11.07 |
Comments