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

 
 
 

思路:维持一个规模为k的移动窗口,对于新的元素,只要在移动窗口中可以找到相同的元素就返回true。

 

代码:

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         Set<Integer> hs = new HashSet<Integer>();
 4         for (int i = 0; i < nums.length; ++i) {
 5             if (hs.contains(nums[i])) return true;
 6             hs.add(nums[i]);
 7             if (i >= k) hs.remove(nums[i - k]);
 8         }
 9         return false;
10     }
11 }

 

posted @ 2017-03-25 13:36  Deribs4  阅读(113)  评论(0编辑  收藏  举报