1、Contains Duplicate
1 class Solution { 2 public: 3 bool containsDuplicate(vector<int>& nums) { 4 for(int i=0; i<nums.size(); i++) 5 { 6 times[nums[i]]++; 7 if(times[nums[i]]>1) 8 return true; 9 } 10 return false; 11 } 12 private: 13 unordered_map<int, int> times; 14 };
2、Contains Duplicate II
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 int len = nums.size(); 5 if(len<1 || k<1) 6 return false; 7 for(int i=0; i<len; i++) 8 { 9 if(times[nums[i]] == 0) 10 times[nums[i]] = i+1; 11 else 12 { 13 if(i+1-times[nums[i]] <= k) 14 return true; 15 else times[nums[i]] = i+1; 16 } 17 } 18 return false; 19 } 20 21 private: 22 unordered_map<int, int> times; 23 };