#-*-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