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

看似簡單,還真有點傷腦筋。。這樣,先把重復(fù)的(要刪除的)全部打上標(biāo)簽'#',還好python 弱類型,不然怎么打標(biāo)簽不會被數(shù)據(jù)撞到還真是麻煩。本來想來一個removeAll(貌似java里面的)多好,可惜list沒有這個方法。排個序,截取list,只要前面的數(shù)字,后面的一律不要,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

表現(xiàn)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容