fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static boolean containsNearbyDuplicateOptimized(int[] nums, int k) {
  5. Map<Integer, Integer> numIndices = new HashMap<>();
  6. for (int i = 0; i < nums.length; ++i) {
  7. if (numIndices.containsKey(nums[i]) && i - numIndices.get(nums[i]) <= k) {
  8. return true;
  9. }
  10. numIndices.put(nums[i], i);
  11. }
  12. return false;
  13. }
  14.  
  15. public static void main(String[] args) {
  16. int[] nums = {1, 1, 3, 1, 2, 3};
  17. int k = 2;
  18. if (containsNearbyDuplicateOptimized(nums, k)) {
  19. System.out.println("There are two equal numbers within distance " + k);
  20. } else {
  21. System.out.println("No two equal numbers found within distance " + k);
  22. }
  23. }
  24. }
Success #stdin #stdout 0.15s 53556KB
stdin
Standard input is empty
stdout
There are two equal numbers within distance 2