Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1] Output: true
Example 2:
Input: [1,2,3,4] Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2] Output: true
난이도 쉬움
여러가지 방법이 있다.
1. 소팅 사용
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
for(int i=0; i<n-1; i++){
if(nums[i] == nums[i+1]){
return true;
}
}
return false;
}
};
2. set 사용
set이 많이 느리넴..
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
set<int> s;
for(int i=0; i<nums.size(); i++){
if(s.find(nums[i]) != s.end())
return true;
s.insert(nums[i]);
}
return false;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 202] Happy Number (0) | 2020.11.25 |
---|---|
[leetcode 204] Count Primes (0) | 2020.11.25 |
[leetcode 172] Factorial Trailing Zeroes (0) | 2020.11.22 |
[leetcode 171] Excel Sheet Column Number (0) | 2020.11.22 |
[leetcode 141] Linked List Cycle (0) | 2020.11.22 |
댓글