Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 28, 2015 04:10
Show Gist options
  • Save dmnugent80/e08b5cffa8441d384453 to your computer and use it in GitHub Desktop.
Save dmnugent80/e08b5cffa8441d384453 to your computer and use it in GitHub Desktop.
Remove Duplicates from Sorted Array
public class Solution {
public int removeDuplicates(int[] A) {
if (A.length == 0) return 0;
int a = A[0];
int count = 0;
for (int i = 1; i < A.length; i++){
if (a == A[i]){
count++;
}
else{
A[i-count] = A[i];
a = A[i];
}
}
return (A.length - count);
}
}
//Testing
public class Test
{
public static void main(String[] args)
{
Solution myObject = new Solution();
int[] arr = {1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7};
int len = myObject.removeDuplicates(arr);
System.out.println("len: " + len);
for (int i = 0; i < arr.length; i++){
System.out.print(String.format("%-3d", arr[i]));
}
}
}
public class Solution {
public int removeDuplicates(int[] A) {
if (A.length == 0) return 0;
int a = A[0];
int count = 0;
for (int i = 1; i < A.length; i++){
if (a == A[i]){
count++;
}
else{
A[i-count] = A[i];
a = A[i];
}
}
return (A.length - count);
}
}
/*output:
len: 7
1 2 3 4 5 6 7 3 3 3 4 4 4 5 5 5 5 5 5 6 7 7 7
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment