217. Contains Duplicate

Description:

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

Algorithm:

  1. Use sort, very easy
  2. 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& nums) {
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 exists(max - min + 1, false);
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)

Leave a Reply

Your email address will not be published. Required fields are marked *