217 - Contains Duplicate
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.
Solution 1: sort then compare the adjacent number
class Solution {
public:
bool containsDuplicate(vector<int>& nums) { //runtime:40ms
if(nums.size()<=)return false;
sort(nums.begin(),nums.end());
for(int i=;i<nums.size();i++){
if(nums[i-]==nums[i])return true;
}
return false;
}
};
Solution 2: map记录已存在的int
class Solution {
public:
bool containsDuplicate(vector<int>& nums) { //runtime:104ms
if(nums.size()<=)return false;
map<int,bool> m;
for(int i=;i<nums.size();i++){
if(m[nums[i]]==true)return true;
m[nums[i]]=true;
}
return false;
}
};
219 - Contains Duplicate II
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int,int> m;
for(int i=;i<nums.size();i++){
if(m.find(nums[i])==m.end())
m[nums[i]]=i;
else{
if(i-m[nums[i]]<=k)
return true;
else
m[nums[i]]=i;
}
}
return false;
}
};