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
看似簡(jiǎn)單锻霎,還真有點(diǎn)傷腦筋楞遏。。這樣叽讳,先把重復(fù)的(要?jiǎng)h除的)全部打上標(biāo)簽'#'褒脯,還好python 弱類(lèi)型便瑟,不然怎么打標(biāo)簽不會(huì)被數(shù)據(jù)撞到還真是麻煩。本來(lái)想來(lái)一個(gè)removeAll(貌似java里面的)多好番川,可惜list沒(méi)有這個(gè)方法胳徽。排個(gè)序,截取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