Leetcode 26. Remove Duplicates from Sorted Array

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

表现
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容