import java.util.*;
public class Main {
public static boolean containsNearbyDuplicateOptimized(int[] nums, int k) {
Map
<Integer, Integer
> numIndices
= new HashMap
<>(); for (int i = 0; i < nums.length; ++i) {
if (numIndices.containsKey(nums[i]) && i - numIndices.get(nums[i]) <= k) {
return true;
}
numIndices.put(nums[i], i);
}
return false;
}
public static void main
(String[] args
) { int[] nums = {1, 1, 3, 1, 2, 3};
int k = 2;
if (containsNearbyDuplicateOptimized(nums, k)) {
System.
out.
println("There are two equal numbers within distance " + k
); } else {
System.
out.
println("No two equal numbers found within distance " + k
); }
}
}
aW1wb3J0IGphdmEudXRpbC4qOwogCnB1YmxpYyBjbGFzcyBNYWluIHsKICAgIHB1YmxpYyBzdGF0aWMgYm9vbGVhbiBjb250YWluc05lYXJieUR1cGxpY2F0ZU9wdGltaXplZChpbnRbXSBudW1zLCBpbnQgaykgewogICAgICAgIE1hcDxJbnRlZ2VyLCBJbnRlZ2VyPiBudW1JbmRpY2VzID0gbmV3IEhhc2hNYXA8PigpOwogICAgICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbnVtcy5sZW5ndGg7ICsraSkgewogICAgICAgICAgICBpZiAobnVtSW5kaWNlcy5jb250YWluc0tleShudW1zW2ldKSAmJiBpIC0gbnVtSW5kaWNlcy5nZXQobnVtc1tpXSkgPD0gaykgewogICAgICAgICAgICAgICAgcmV0dXJuIHRydWU7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgbnVtSW5kaWNlcy5wdXQobnVtc1tpXSwgaSk7CiAgICAgICAgfQogICAgICAgIHJldHVybiBmYWxzZTsKICAgIH0KIAogICAgcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewogICAgICAgIGludFtdIG51bXMgPSB7MSwgMSwgMywgMSwgMiwgM307CiAgICAgICAgaW50IGsgPSAyOwogICAgICAgIGlmIChjb250YWluc05lYXJieUR1cGxpY2F0ZU9wdGltaXplZChudW1zLCBrKSkgewogICAgICAgICAgICBTeXN0ZW0ub3V0LnByaW50bG4oIlRoZXJlIGFyZSB0d28gZXF1YWwgbnVtYmVycyB3aXRoaW4gZGlzdGFuY2UgIiArIGspOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIFN5c3RlbS5vdXQucHJpbnRsbigiTm8gdHdvIGVxdWFsIG51bWJlcnMgZm91bmQgd2l0aGluIGRpc3RhbmNlICIgKyBrKTsKICAgICAgICB9CiAgICB9Cn0=