- Total Accepted: 199594
- Total Submissions: 563740
- Difficulty: Easy
- Contributors: Admi
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.
思路:使用index記住當前位置,從下標1開始遍歷list,如果重複則替換index+1的位置。返回index+1.
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:return 0
ind=0;i=1
while i<len(nums):
if nums[ind]!=nums[i]:
ind+=1;nums[ind]=nums[i]
i+=1
return ind+1