# &amp;lt;LeetCode&amp;gt;&amp;lt;Easy&amp;gt; 26 Remove Duplitcates from Sorted Array

2015-10-17 19:19:20来源:CSDN作者:awsxsa人点击

Given a sorted array, remove the duplicates in place such that each element appear only once and 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 nums = `[1,1,2]`,

Your function should return length = `2`, with the first two elements of nums being `1` and `2` respectively. It doesn't matter what you leave beyond the new length.

#Python2  TimeOut  未考虑正序序列

`class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        i=0        while i<len(nums):            # try:n =nums[i]            # except:return nums            if nums[i] in nums[:i]:nums.pop(i)            else:i+=1`

#Python2 156ms

`class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        if nums is []:return        i=1        while i<len(nums):            if nums[i] == nums[i-1]:nums.pop(i)            else:i+=1`

#Python 132ms   减少长度计算

`class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        if nums is []:return        i=1        while 1:            try:tmp=nums[i]            except:return                    if tmp == nums[i-1]:nums.pop(i)            else:i+=1        `

#Python2  136ms

#设置暂存量

`class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums) <2:return        i,last=1,nums[0]        while 1:            try:tmp=nums[i]            except:return            if tmp == last:nums.pop(i)            else:i+=1            last=tmp`

#Python2 128ms

#减少重复

`class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums) <2:return        i,last=1,nums[0]        while 1:            try:                tmp=nums[i]            except:return            if tmp == last:nums.pop(i)            else:                i+=1                last=tmp            `

无相关信息