Description:
https://leetcode.com/problems/contains-duplicate/#/description
Algorithm:
- Use sort, very easy
- Don’t use sort, use a array to record the appearance of words. If a word appears for more than 1 times, return true.
Code1:
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
if (nums.size() < 2) return false;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 1;i++)
{
if (nums[i] == nums[i+1])
return true;
}
return false;
}
};
Code2:
class Solution {
public:
bool containsDuplicate(vector
int min = INT_MAX;
int max = INT_MIN;
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > max) {
max = nums[i];
}
if (nums[i] < min) {
min = nums[i];
}
}
vector
for (int i = 0; i < nums.size(); ++i) {
if (exists[nums[i] - min]) {
return true;
}
else {
exists[nums[i] - min] = true;
}
}
return false;
}
};
Time & Space:
Code1:
Time: O(nlogn) Space O(1)
Code2:
Time: O(n), Space O(n)