Skip to content

Instantly share code, notes, and snippets.

@durgaswaroop
Created January 6, 2018 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durgaswaroop/a3b4ce78d4a1626b14ade072ea941cd2 to your computer and use it in GitHub Desktop.
Save durgaswaroop/a3b4ce78d4a1626b14ade072ea941cd2 to your computer and use it in GitHub Desktop.
Remove duplicate elements from an array
/* Remove duplicate elements from an array */
// Code inside the method is presented here
int[] numbers = {1, -2, 3, 1, 0, 9, 5, 6, 4, 5};
System.out.println("Input array: " + Arrays.toString(numbers));
Arrays.sort(numbers);
int j = 0; // Slow moving index
// i is the fast moving index that loops through the entire array
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] != numbers[j]) {
j++;
numbers[j] = numbers[i];
}
}
int[] result = Arrays.copyOf(numbers, j + 1);
System.out.println("Final result after removing duplicates: " + Arrays.toString(result));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment