Created
January 6, 2018 17:38
-
-
Save durgaswaroop/a3b4ce78d4a1626b14ade072ea941cd2 to your computer and use it in GitHub Desktop.
Remove duplicate elements from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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