Delete duplicates in a sorted array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.