26. Remove Duplicates from Sorted Array

题目:

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.

代码:

题目理解没什么难点,就是对排好序的数,去除重复的,还剩下几个。

但题目要求内存不能增加,就是说不能新建数据结构,但可以删除现有的list :)

于是乎:

#-*- utf-8 -*-
#Remove Duplicates from Sorted Array
class Solution(object):
    def removeDuplicates(self, nums):
        total_length = len(nums)
        for index,value in enumerate(nums):
            if index == total_length -1:break

    #遇到后一个元素和该元素一样,就删除该元素,一直到没有一样的为止
            while nums[index]==nums[index+1]:         
                list.remove(nums, nums[index])
                #index = index+1
                total_length = total_length-1   
                if index == total_length -1:break
            #print nums
        return total_length

if __name__=="__main__":
    nums=[-49,-49,-48,-48,-47,-47,-47,-46,-46,-46,-46,-44,-44,-44,-42,-42,-41,-41,-40,-40,-39,-39,-39,-38,-37,-37,-36,-36,-35,-35,-35,-34,-34,-32,-32,-31,-30,-29,-28,-28,-27,-27,-27,-26,-26,-25,-25,-25,-24,-23,-22,-21,-21,-21,-20,-20,-20,-20,-20,-18,-18,-17,-17,-16,-16,-15,-15,-15,-14,-13,-13,-11,-10,-10,-9,-9,-9,-9,-9,-9,-7,-6,-6,-6,-5,-5,-5,-4,-3,-3,-1,-1,-1,-1,-1,1,3,3,5,5,5,5,6,6,7,8,8,8,8,9,9,10,10,13,14,14,14,15,15,15,16,17,18,18,19,19,20,20,20,21,21,21,22,23,23,24,25,25,25,25,26,26,26,26,26,27,27,27,27,27,27,27,28,29,29,30,30,30,30,31,31,32,32,34,35,37,38,39,39,39,41,43,44,44,44,45,45,45,46,48,49,49,49,49,50]
    a = Solution()
    print "result: %d" %(a.removeDuplicates(nums))
    print nums

实现是实现了,但是用了500多ms~~。说明还有很大提升空间!

 

百度了一下,发现自己又犯蠢了,稍做修改,即可大范围提高效率:

    def removeDuplicates(self, nums):
        #total_length = len(nums)
        if len(nums) == 0:return None
        result=1
        for index in range(0,len(nums)-1):
            #判断后面的元素不等于前面的元素,就计数+1,并且赋值到数组前段
            if nums[index+1] != nums[index]:  
                nums[result] = nums[index+1]
                result=result+1                
        return result   

76ms哦:

posted @ 2016-09-05 17:57  PolarBearInterest  阅读(121)  评论(0编辑  收藏  举报