相关信息:
LeetCode链接:
https://leetcode-cn.com/problems/contains-duplicate-ii/
代码:
//作者:LeetCode-Solution
import java.util.HashMap;
import java.util.Map;
public class L221 {
public static void main(String[] args) {
//Test
int[] nums = {1, 2, 3, 1};
int k = 3;
Solution221 solutionL1220 = new Solution221();
boolean ans =solutionL1220.containsNearbyDuplicate(nums,k);
System.out.println(ans);
}
}
class Solution221 {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap();
int length = nums.length;
for (int i = 0; i < length; i++) {
int num = nums[i];
if (map.containsKey(num) && i - map.get(num) <= k) {
//Encountered a value that exists in the map and the distance between them is less than or equal to K
return true;
}
//update index of num
map.put(num, i);
}
return false;
}
}