Leetcode "Remove duplicates from Sorted Array II" Python implementation

Source: Internet
Author: User

title :

Follow up for "Remove duplicates":
What if duplicates is allowed at the most twice?

For example,
Given sorted Array A = [1,1,1,2,2,3] ,

Your function should return length = 5 , and A is now [1,1,2,2,3] .

code : OJ Test via runtime:120 ms

1 classSolution:2     #@param a a list of integers3     #@return An integer4     defremoveduplicates (Self, A):5         ifLen (A) < 3 :6             returnLen (A)7         8Pre =09Curr = 1Ten          forIinchRange (2, Len (A)): One             ifA[i] = = A[curr] andA[i] = =A[pre]: A                 Continue -             Else: -A[curr+1],a[i] = a[i],a[curr+1] thePre + = 1 -Curr + = 1 -          -         returnCurr+1

Ideas :

First the length less than 3 can be returned directly, which saves a lot of things.

The main logic is: starting from the third element, whether the current element i is equal to the first two elements, if equal, I continue to go down, if not, then Exchange curr+1 and I position elements

Brush a few of the questions of the array, feeling there are some similar tricks, is to only traverse once, do not meet the conditions to exchange element position. Does not occupy additional space.

Leetcode "Remove duplicates from Sorted Array II" Python implementation

Related Article

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.