[Leetcode] [Python]26:remove duplicates from Sorted Array

Source: Internet
Author: User

#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '

26:remove Duplicates from Sorted Array
https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/

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].

===comments by dabay===
One loop, two pointers, one pointing to the last inserted position, the other one going straight ahead.
If the number of two pointers is the same, the number second pointer continues to go.
If not, insert the number pointing at number second into the back of the number of pointers.
Finally with the new array, returns the length.
‘‘‘

Class Solution:
# @param a list of integers
# @return An integer
def removeduplicates (self, A):
I,j = 0,0
While J < Len (A):
If a[i]! = A[j]:
i + = 1
A[i] = A[j]
J + = 1
A = a[:i+1]
Return Len (A)


def main ():
Sol = solution ()
Print Sol.removeduplicates ([1,1,2])


if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)

[Leetcode] [Python]26:remove duplicates from Sorted Array

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.