1 """
2 Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
3 Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
4 Example 1:
5 Given nums = [1,1,2],
6 Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
7 It doesn't matter what you leave beyond the returned length.
8 Example 2:
9 Given nums = [0,0,1,1,1,2,2,3,3,4],
10 Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
11 It doesn't matter what values are set beyond the returned length.
12 """
13 """
14 本题的关键是不用新开辟数组
15 而是用一个指针来在原数组上存放结果
16 """
17
18 class Solution:
19 def removeDuplicates(self, nums):
20 if not nums:
21 return 0
22 j = 0 #用来借用原数组上的空间存答案数组的指针
23 for i in range(1, len(nums)):
24 if nums[i] != nums[i-1]:
25 j += 1
26 nums[j] = nums[i]
27 return j+1