Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. package com.hrishikesh.practices.array;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Map;
  7. import java.util.Set;
  8.  
  9. /**
  10. * Problem:
  11. * Contains Duplicate in array at most far k
  12. * Given an array of integers and an integer k, find out whether there are two distinct indices i and j
  13. * in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
  14. *
  15. * @author hrishikesh.mishra
  16. */
  17. public class ArrayDuplicate {
  18.  
  19. public static boolean find(int[] array, int k) {
  20.  
  21. Map<Integer, Set<Integer>> map = new HashMap<>();
  22.  
  23. for (int i = 0; i < array.length; i++) {
  24.  
  25. if (map.containsKey(array[i])) {
  26. Set<Integer> indices = map.get(array[i]);
  27.  
  28. for (Integer index : indices) {
  29. if (Math.abs(index - i) <= k) {
  30. return true;
  31. }
  32. }
  33.  
  34. map.get(array[i]).add(i);
  35. } else {
  36. Set<Integer> set = new HashSet<>();
  37. set.add(i);
  38. map.put(array[i], set);
  39. }
  40. }
  41.  
  42. return false;
  43. }
  44.  
  45. }
  46.  
  47. class ArrayDuplicateTest {
  48. public static void main(String[] args) {
  49. int[] array = {1, 3, 4, 2, 1, 5};
  50. int k = 2;
  51. System.out.println("Array: " + Arrays.toString(array));
  52. System.out.println("K : " + k);
  53. System.out.println("Is exists? " + ArrayDuplicate.find(array, k));
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement