Since the array is sorted, all duplicates will be adjacent. Iterate through the array and maintain a variable(nonDuplicateIndex) which will refer the latest index in array which contains non duplicate element while iteration.Lets us assume initially nonDuplicateIndex=0. While iteration through given
int[] arr={1,2,3,4,4,4,5,6,8,8,9} whenever arr[nonDuplicateIndex] !=arr[indexofIteration] then nonDuplicateIndex increments and assign value as arr[nonDuplicateIndex++]=arr[indexofIteration]. whenever it finds duplicate values in array, it does not increment and wait for the non duplicate value.As soon as it finds non duplicate value again it assign value as [nonDuplicateIndex++]=arr[indexofIteration]. So variable 'nonDuplicateIndex' represents non duplicate elements so far. At the end of iteration nonDuplicateIndex will be last element of array after removing duplicate. The elements after nonDuplicateIndex can be set to zero till array length.
Here is a sample example:
import java.util.Arrays;
public class RemoveDuplicatefromSortedArray {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 4, 4, 5, 6, 8, 8, 9 };
removeDuplicate(arr);
System.out.println("Modified Array:" + Arrays.toString(arr));
}
private static void removeDuplicate(int[] arr) {
int nonDuplicateElementIndexSoFar = 0;
for (int i = 1; i < arr.length; i++) {
if (!(arr[nonDuplicateElementIndexSoFar] == arr[i])) {
nonDuplicateElementIndexSoFar++;
arr[nonDuplicateElementIndexSoFar] = arr[i];
}
}
for (int j = nonDuplicateElementIndexSoFar + 1; j < arr.length; j++) {
arr[j] = 0;
}
}
}
int[] arr={1,2,3,4,4,4,5,6,8,8,9} whenever arr[nonDuplicateIndex] !=arr[indexofIteration] then nonDuplicateIndex increments and assign value as arr[nonDuplicateIndex++]=arr[indexofIteration]. whenever it finds duplicate values in array, it does not increment and wait for the non duplicate value.As soon as it finds non duplicate value again it assign value as [nonDuplicateIndex++]=arr[indexofIteration]. So variable 'nonDuplicateIndex' represents non duplicate elements so far. At the end of iteration nonDuplicateIndex will be last element of array after removing duplicate. The elements after nonDuplicateIndex can be set to zero till array length.
Here is a sample example:
import java.util.Arrays;
public class RemoveDuplicatefromSortedArray {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 4, 4, 5, 6, 8, 8, 9 };
removeDuplicate(arr);
System.out.println("Modified Array:" + Arrays.toString(arr));
}
private static void removeDuplicate(int[] arr) {
int nonDuplicateElementIndexSoFar = 0;
for (int i = 1; i < arr.length; i++) {
if (!(arr[nonDuplicateElementIndexSoFar] == arr[i])) {
nonDuplicateElementIndexSoFar++;
arr[nonDuplicateElementIndexSoFar] = arr[i];
}
}
for (int j = nonDuplicateElementIndexSoFar + 1; j < arr.length; j++) {
arr[j] = 0;
}
}
}
No comments:
Post a Comment