Description:
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 by modifying the input array in-place with O(1) extra memory.
Example:
Given 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就是数组中不同数字的个数,代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if(len(nums) == 0):
return 0;
p = q = 0;
while(p<len(nums) and q < len(nums)):
if(nums[p] == nums[q]):
q+=1;
else:
p+=1;
nums[p] = nums[q];
return p+1;