Leetcode 26. Remove Duplicates f

2017-05-13  本文已影响0人  AlexSun1995

Question

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.

Subscribe to see which companies asked this question.

Balabala

看似简单,还真有点伤脑筋。。这样,先把重复的(要删除的)全部打上标签'#',还好python 弱类型,不然怎么打标签不会被数据撞到还真是麻烦。本来想来一个removeAll(貌似java里面的)多好,可惜list没有这个方法。排个序,截取list,只要前面的数字,后面的一律不要,done.

Code

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        pre = '#'
        size = len(nums)
        cnt = 0
        for i in range(size):
            if pre == nums[i]:
                nums[i] = '#'
            else:
                pre = nums[i]
                cnt += 1
        nums.sort()
        nums = nums[0:cnt]
        return cnt

Performance

表现
上一篇下一篇

猜你喜欢

热点阅读