Remove duplicates from sorted Array

Source: Internet
Author: User

Given a sorted array, remove the duplicates in place such that each element appear onlyOnceAnd return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array A =[1, 1, 2],

Your function shocould return length =2, And a is now[1, 2].

Idea: Because the input data is ordered, we only need to compare the current element with the end element of the new sequence. If it is the same, the current element is skipped; otherwise, the current element is added to the end of the new sequence.

 1   Class Solution {  2   Public  :  3       Int Removeduplicates ( Int A [], Int  N ){  4           If (N = 0 ){ Return   0  ;}  5          Int Pos = 0  ;  6           For ( Int I = 1 ; I <n; ++ I ){  7               If (A [POS]! = A [I]) {A [++ POS] = A [I];}  8   }  9           Return Pos +1  ;  10   }  11 };

 

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.