Leetcode (6) Remove duplicates from Sorted Array

Source: Internet
Author: User

Title Description

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

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

For example,
Given input Array A = [1,1,2],

Your function should return length = 2, and A is now [all].

Thinking of solving problems

The topic requires removing the extra elements in the sorted array, changing the array and returning the number of new arrays. That is, the original array is a = [1,1,2], the result of processing should be a = [1,2,*], the different element 2 is placed after 1, and the length of the returned array is 2.

The method can be implemented by using two array ordinal index or pointer. The first index points to the last valid element, the second index iterates backwards, and if the current traversal element is different from the index element, the index is shifted one bit, and the element that the second index points to is paid to the element of the first index. Finally, return to the position of index. Time of the time of the MS, relatively slow ~ do not know if you have a better idea, welcome message ~ ~ ~

class  solution  { public : int  removeduplicates (int  a[],  int  N) {int  count  = 0 ; for         (int  i = 1 ; i < n; i++) {if  (a[i] = = A[i-1 ]) count  + +; else         A[i-count ] = a[i];    } return  n-count ; }};

Leetcode (6) 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.