Leetcode: 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.

 Better idea is to maintain a hashset that contains at most k numbers

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         Set<Integer> set = new HashSet<Integer>();
 4         for(int i = 0; i < nums.length; i++){
 5             if(set.contains(nums[i])) return true;
 6             set.add(nums[i]);
 7             if(set.size()>k) set.remove(nums[i-k]);
 8         }
 9         return false;
10     }
11 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/5052896.html