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.
1 class Solution { 2 public: 3 bool containsDuplicate(vector<int>& nums) { 4 if(nums.size()==0) return false; 5 sort(nums.begin(),nums.end()); 6 int tmp=nums[0]; 7 8 for(int i=1;i<nums.size();i++) 9 { 10 if(nums[i]==tmp) 11 return true; 12 else 13 tmp=nums[i]; 14 } 15 16 return false; 17 } 18 };
II:
Given an array of integers and an integer k,
return true if and only if there are two distinct indices i and j in the array such that nums[i] = nums[j]
and the difference between i and j is at most k.
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 if(nums.size()==0) return false; 5 //if(k>nums.size()) return false; 6 7 map<int,int> tmp; 8 for(int i=0;i<nums.size();i++) 9 { 10 if(tmp.find(nums[i])!=tmp.end()&&i-tmp[nums[i]]<=k) 11 { 12 return true; 13 }else 14 { 15 tmp[nums[i]]=i; 16 } 17 } 18 19 return false; 20 } 21 };