Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
Could anyone tell me why the test case below is true?
[1,0,1,1]
1
The largest difference should be 2 which is greater than k = 1. Isn't it?
You are right, 2 is larger than 1. However we still have other equal numbers which the difference of their abs value is <= 1. This means you should update the initial index of the value you mapped, initially 1 is mapped with 0 right, but later on it should be updated and mapped to 2. This would mean that abs values (2 - 3) <= 1...
for(int i = 0; i<nums.length; i++)
{
if(map.containsKey(nums[i]) == true)
{
if(Math.abs(map.get(nums[i]) - i) <= k)
{
duplicate = true;
}
map.put(nums[i], i); // the update i was talking about
}
else
{
map.put(nums[i], i);
}
}