[Leetcode]26. Remove Duplicates from Sorted Array

Source: Internet
Author: User

Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.

Do the allocate extra space for another array, and you must does this on place with constant memory.

For example,
Given input array nums = [1,1,2] ,

your function should return length = 2 , with the first elements of  nums  being 1  and 2  respectively. It doesn ' t matter what are you leave beyond the new length.


Test instructions

Removes the repeating element, based on the given sorted array, and returns the length of the array after the duplicate element is deleted. But to apply for extra space.


Ideas:

1) If the array length is 1 or 0, return directly.

2) Compare the current position element of the array with the next position element, if it is equal, do not need to do anything, if not the same, then the non-repeating array is labeled Nlen plus one, and replace the second one.

3) * (Nums + nlen) = * (Nums + CNT + 1) Statement Description: If there is no duplicate element, then Nlen = = cnt + 1, if duplicate elements are present, then Nlen is the duplicate element location, with the non-repeating element cnt + 1 replaced (such as 1,2,2,3 at this time 2,3 the first element is a repeating element, you can replace it)

Int removeduplicates (int* nums, int numssize) {    if  (  numssize == 1 | |  numsSize == 0 )      {            return numsSize;    }        /* 1 2 2 3 4*/    int cnt  = 0;     int nLen = 0;    for  ( cnt = 0;  cnt < numssize - 1; cnt += 1 )      {            if  ( * (nums + cnt)  !=  * (nums + cnt + 1)  )         {                nLen += 1;            * ( nums + nLen )  =  * (nums + cnt + 1);         }        }       return nlen + 1;}


[Leetcode]26. Remove Duplicates from 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.