Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. package com.hrishikesh.practices.array;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.List;
  6.  
  7. import static com.hrishikesh.practices.array.DuplicatesNumbersInArray.findDuplicate;
  8.  
  9. /**
  10. * Problem:
  11. * Duplicates in an Array in O(n)
  12. * Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear more than one time
  13. * and others appear once.
  14. * Find duplicate items.
  15. * ;
  16. * ;
  17. * Facts:
  18. * - Total size of array is n
  19. * - Element in array is between 1 and n
  20. * - Some element could be repeated twice
  21. *
  22. * @author hrishikesh.mishra
  23. */
  24. public class DuplicatesNumbersInArray {
  25.  
  26. public static List<Integer> findDuplicate(int[] array) {
  27.  
  28. /** To hold duplicate elements **/
  29. List<Integer> result = new ArrayList<>();
  30.  
  31. /** Length of array **/
  32. int n = array.length;
  33.  
  34. /**
  35. * Iterate array from start to end
  36. * Mark convert each element to negative
  37. * Now, if element is already negative,
  38. * that means the pointer, which pointing to this element has seen before and
  39. * that means that is duplicate element
  40. */
  41. for (int i = 0; i < n; i++) {
  42.  
  43. /** Check element is already converted to negative or not **/
  44. if (array[Math.abs(array[i]) - 1] >= 0) {
  45. /** If not converted to negative, means we are reading it first time **/
  46. array[Math.abs(array[i]) - 1] = -array[Math.abs(array[i]) - 1];
  47. } else {
  48. /** If element is negative then, pointer which point this element is duplicate **/
  49. result.add(Math.abs(array[i]));
  50. }
  51.  
  52. }
  53.  
  54. /** Return duplicate element **/
  55. return result;
  56. }
  57. }
  58.  
  59. class DuplicatesNumbersInArrayTest {
  60. public static void main(String[] args) {
  61. int[] array1 = {1, 2, 2, 4};
  62. int[] array2 = {4, 3, 2, 7, 8, 2, 3, 1};
  63. int[] array3 = {10, 2, 5, 10, 9, 1, 1, 4, 3, 7};
  64.  
  65. System.out.println("Array : " + Arrays.toString(array1));
  66. System.out.println("Duplicate: " + findDuplicate(array1));
  67.  
  68. System.out.println("Array : " + Arrays.toString(array2));
  69. System.out.println("Duplicate: " + findDuplicate(array2));
  70.  
  71. System.out.println("Array : " + Arrays.toString(array3));
  72. System.out.println("Duplicate: " + findDuplicate(array3));
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement