Contains Duplicate II
来自 <https://leetcode.com/problems/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 jis at most k.
题目解读
给定一个整型数组和整数k,找出数组中是否存在不同的i和j,使得nums[i] = nums[j] ,并且i与j之间的距离最大是k。
解析
使用set,逐个向set中添加元素,使set中的元素个数小于k个。当set中的元素达到k个的时候,将在set中最早加入的删除,然后再向set中添加元素。
Java代码:
public boolean containsNearbyDuplicate(int[] nums, int k) { if(null == nums) return false; Set<Integer> result = new HashSet<Integer>(); int start = 0; int end =0; for(int i=0; i<nums.length; i++) { if(result.contains(nums[i])) { return true; } else { result.add(nums[i]); end++; } if((end - start) > k){ result.remove(nums[start]); start++; } } return false; }
算法性能: