[LeetCode] 219. Contains Duplicate II 解题思路

Given an array of integers and an integer k, find out whether 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.

问题:给定一个数组和整数 k ,判断是否存在两个相等元素,并且两个相等元素的下标差在 k 以内?

问题问是否存在一个子数组满足某种条件,首先想到的是滑动窗口(sliding window)的模型。

将 [0, k] 视为一个窗口,将窗口向右滑动直到滑到最右端,期间判断窗口中是否存在相等元素。只要其中一个窗口存在相等元素,即原题目存在相等元素,否则,不存在。

判断一个数是否存在于一个集合中,可以用 hash_table ,即 c++ 中的 unordered_map。

 

本题目的思路使用的是长度固定的滑动窗口,其他同样可以理解为滑动窗口的还有:

Search Insert Position,每次长度减半的滑动窗口

Minimum Size Subarray Sum ,  求最大/最小连续子数组的滑动窗口。窗口长度无规律。

 1     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 2         
 3         if(k == 0){
 4             return false;
 5         }
 6         
 7         unordered_map<int, int> int_cnt;
 8         
 9         for(int i = 0 ; i <= k && i < nums.size() ; i++){
10             if(int_cnt.count(nums[i]) == 0){
11                 int_cnt[nums[i]] = 1;
12             }else{
13                 return true;
14             }
15         }
16         
17         for (int i = 1; (i + k) < nums.size(); i++){
18             int_cnt.erase(nums[i-1]);
19             
20             if(int_cnt.count(nums[i+k]) == 0){
21                 int_cnt[nums[i+k]] = 1;
22             }else{
23                 return true;
24             }
25         }
26         
27         return false;
28     }

 

posted @ 2016-01-17 19:10  TonyYPZhang  阅读(352)  评论(0编辑  收藏  举报