本文共 1318 字,大约阅读时间需要 4 分钟。
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.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
注意步长为零的情况
双指针
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { int i = 0, j = 0; while(i < nums.length-1){ if(j - i == k || j == nums.length-1) { j = ++i; continue;} j++; if(nums[i] == nums[j]) return true; } return false; }}
HashSet
class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { int i = 0; Setset = new HashSet<>(); while(i < nums.length){ if(set.contains(nums[i])) return true; else set.add(nums[i]); if(set.size() == k+1) set.remove(nums[i-k]); i++; } return false; }}
HashSet的add方法是先判断set是否含有元素,可以简化solution2的步骤
public boolean containsNearbyDuplicate(int[] nums, int k) { Setset = new HashSet (); for(int i = 0; i < nums.length; i++){ if(i > k) set.remove(nums[i-k-1]); if(!set.add(nums[i])) return true; } return false; }
转载地址:http://ybqvb.baihongyu.com/