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.
solution:
Use hashmap, key is the element value, value is the element index.
O(n)
public boolean containsNearbyDuplicate(int[] nums, int k) {
int len = nums.length;
if(len <= 1) return false;
Map<Integer, Integer> count = new HashMap<>();
for(int i = 0;i < len; i++) {
if(count.containsKey(nums[i])) {
if(Math.abs(count.get(nums[i]) - i) <= k) return true;
}
count.put(nums[i], i);
}
return false;
}

本文介绍了一个算法,用于在给定数组和整数k的情况下,判断是否存在两个不同的索引,使得它们对应的元素相等且索引之差不超过k。使用哈希表实现O(n)的时间复杂度。
133

被折叠的 条评论
为什么被折叠?



