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)