[leetcode] Contains Duplicate II

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 i and j is at most k.

Have you met this question in a real interview?
 
方法一:
分析:可以直接定义一个长度最大为k的滑动窗口,用一个set维护窗口内的数字判断是否出现重复,使用两个指针start和end标记滑动窗口的两端,初始都是0,然后end不断进行扩展,扫描元素判断是否出现重复元素,直到发现end-start>k, 就开始移动start,并且在set中移除对应的元素。如果以为扫描到数组末尾还没有发现重复元素,那就可以返回false。时间复杂度和空间复杂度都是 O(N)。
 1 class Solution
 2 {
 3 public:
 4   bool containsNearbyDuplicate(vector<int> &nums, int k)
 5   {
 6     set<int> S;
 7     int start = 0, end  = 0;
 8 
 9     for(int i=0; i<nums.size(); i++)
10     {
11       if(S.find(nums[i]) != S.end())
12         return true;
13       else
14       {
15         S.insert(nums[i]);
16         end++;
17       }
18 
19       if(end-start > k)
20       {
21         S.erase(nums[start]);
22         start++;
23       }
24     }
25 
26     return false;
27   }
28 };
 
方法二:
使用map记录出现过的nums[i],并记录对应的位置i,当出现冲突时,比较两者位置关系,如果小于等于k,则返回true,否则记录新位置;如果没有冲突,则说明不含有重复元素。
 1 class Solution
 2 {
 3 public:
 4   bool containsNearbyDuplicate(vector<int> &nums, int k)
 5   {
 6     map<int, int> M;
 7 
 8     for(int i=0; i<nums.size(); i++)
 9     {
10       if(M.find(nums[i]) != M.end() && i-M[nums[i]] <= k)
11         return true;
12       else
13         M[nums[i]] = i;
14     }
15 
16     return false;
17   }
18 };
原文地址:https://www.cnblogs.com/lxd2502/p/4595205.html