fork download
  1. import java.util.*;
  2.  
  3. class Main {
  4. public static boolean nearbyDupli(int[] nums, int k) {
  5. Map<Integer, Integer> map = new HashMap<>();
  6.  
  7. for (int i = 0; i < nums.length; ++i) {
  8. if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
  9. return true;
  10. }
  11. map.put(nums[i], i);
  12. }
  13. return false;
  14. }
  15.  
  16. public static void main(String[] args) {
  17. Scanner sc=new Scanner(System.in);
  18. int n=sc.nextInt();
  19. int[] nums = new int[n];
  20. for(int i=0;i<n;i++){
  21. nums[i]=sc.nextInt();
  22. }
  23. int k = sc.nextInt();
  24. if (nearbyDupli(nums, k)) {
  25. System.out.println("There are two equal numbers within distance " + k);
  26. } else {
  27. System.out.println("No two equal numbers found within distance " + k);
  28. }
  29. sc.close();
  30. }
  31. }
Success #stdin #stdout 0.21s 56904KB
stdin
7
1 2 3 1 2 3 2
2
stdout
There are two equal numbers within distance 2