LeetCode OJ:Contains DuplicateII(是否包含重复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 jis at most k.

这题上上一篇博客的延伸,问的是k长的距离内有没有两个数是相等的,类似一个滑动窗口问题,方法比较简单,使用一个map记下上次数出现的位置就可以了,代码如下:

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         map<int, int> ret;
 5         int sz = nums.size();
 6         for (int i = 0; i < sz; ++i){
 7             if (ret.find(nums[i]) != ret.end() && i - ret[nums[i]] <= k)
 8                 return true;
 9             else
10                 ret[nums[i]] = i;
11         }
12         return false;
13     }
14 };

java版本的代码如下所示,用的方法都是一样的:

 1  public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
 4         for(int i = 0; i < nums.length; ++i){
 5             if(m.containsKey(nums[i]))
 6                 if(i-m.get(nums[i]) <= k)
 7                     return true;
 8                 m.put(nums[i], i);//放在这里有两个原因,如果本来存在将index更新到最近的位置,如果不存在就将它放到map中起
 9         }
10         return false;        
11     }
12 }
原文地址:https://www.cnblogs.com/-wang-cheng/p/4887494.html