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,求不超过最大间隔的区间 是否有两个相等的数。
2.解题思路:
维护一个set 见代码
3.代码
[title] [] [url] [link text]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclass{ publicbooleancontainsNearbyDuplicate(int[] nums, int k){ HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < nums.length; i++) { if (set.contains(nums[i])) returntrue; set.add(nums[i]); if (i >= k) { set.remove(nums[i - k]); } } returnfalse; } }
近期评论