Share a simple algorithm: Delete duplicates in sorted array
Given a sorted array, you need to delete the repeating elements in place so that each element appears only once, returning the new length of the array after removal.
Instead of using extra array space, you must modify the input array in place and complete it with O (1) Extra space.
Example 1:
Language: Java
public int removeduplicates (int[] nums) {
if (Nums.length = = 0) return 0;
int i = 0;
for (int j = 1; j < Nums.length; J + +) {
if (nums[j]! = Nums[i]) {
i++;
Nums[i] = Nums[j];
}
}
return i + 1;
}
Once the array is sorted, we can place two pointersI andJ, whereI is a slow pointer, andJ is a fast pointer. Just< Span class= "base textstyle uncramped" >nu ms[i]=nu ms[j< Span class= "Mord mathit" >j to skip duplicates.
When we meetNUMS[J]≠NUMS[I], skipping the run of duplicates has ended, so we have to put it (NUMS[J]) is copied to the value of theNums[i + 1]< Span class= "Mord mathit" > < Span class= "Mord mathit" >i, then we will repeat the same process again until j arrives at the end of the array.
< Span class= "Mord mathit" > time complexity: < Span class= "Katex-mathml" >o (n)
Note: Once the array is sorted, the repeating values are skipped directly, and the duplicates are grouped into the array.
Delete duplicates in a sorted array