这道题为简单题
题目:
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.
思路:
由于列表为有序的,所以我就用的两个指针,把不同的元素移到数组前面
代码:
1 class Solution(object): 2 def removeDuplicates(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 8 j = 0 9 if len(nums)<1: return 0 10 for i in range(1, len(nums)): 11 if nums[i] != nums[j]: 12 j += 1 13 nums[i], nums[j] = nums[j], nums[i] 14 15 return j+1