Advertisement
Guest User

Untitled

a guest
May 5th, 2015
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. public class ArrayUtil {
  2.  
  3. /**
  4. * Field INPUT_LESS_THAN_TWO. (value is 2)
  5. */
  6. private static final int INPUT_LESS_THAN_TWO = 2;
  7.  
  8. /**
  9. * Method removeDuplicateElement. Given a sorted array of integers, this
  10. * method removes the duplicate elements. Input array is sorted array and
  11. * can have only negative values, only positive value or a mix of both.
  12. *
  13. * @param inputArray
  14. * int[]
  15. *
  16. * @return int[]
  17. * @throws IllegalArgumentException
  18. */
  19. public int[] removeDuplicateElement(final int[] inputArray)
  20. throws IllegalArgumentException {
  21.  
  22. int j = 0; // Marks the begining of the array
  23. int i = 1; // Points toward the second element in the array
  24.  
  25. if (null == inputArray || 0 == inputArray.length) {
  26. throw new IllegalArgumentException(
  27. "Input Array is either null or of zero length");
  28. } // end of null and 0 length check
  29.  
  30. // Return if the input array has only one item
  31. if (inputArray.length < INPUT_LESS_THAN_TWO) {
  32. return inputArray;
  33. } // end of check for length less than 2
  34. while (i < inputArray.length) {
  35. if (inputArray[i] == inputArray[j]) {
  36. i++;
  37. } else {
  38. inputArray[++j] = inputArray[i++];
  39. }
  40. } // end of while loop
  41.  
  42. // copy and return the array
  43. final int[] outputArray = new int[j + 1];
  44. for (int k = 0; k < outputArray.length; k++) {
  45. outputArray[k] = inputArray[k];
  46. }
  47.  
  48. return outputArray;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement