[刷题] LeetCode 219 Contains Duplicate II

Claim

  • Nums given integer array and integer k, the presence of indexes i and j, the difference between the nums [i] == nums [j], i, and j and k does not exceed

Thinking

  • Violence solution (n2)
  • Establishing a sliding window of up to k + 1, the element lookup table lookup (time n, the space k)
 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         
 5         unordered_set<int> record;
 6         for( int i ; i < nums.size() ; i ++ ){
 7             if( record.find(nums[i]) != record.end() )
 8                 return true;
 9             record.insert( nums[i] );
10             
11             // 保持record中最多有k个元素 
12             if( record.size() == k+1 )
13                 record.erase( nums[i-k] );
14         }
15         return false; 
16     }
17 };
View Code

Related

  • 217 Contains Duplicate

Guess you like

Origin www.cnblogs.com/cxc1357/p/12624599.html