题目描述
Given a sorted array nums, 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 1:
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 returned length.
- mode: easy
- tag: array(数组)
双指针法
- 时间复杂度: O ( N ) O(N) O(N)
- 空间复杂度: O ( 1 ) O(1) O(1)
Python
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if len(nums)<2:
return len(nums);
// idx记录已经找到的非重复数值
idx=0
for i in range(len(nums)):
if nums[idx]!=nums[i]:
idx+=1
nums[idx]=nums[i]
return index+1
C++
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int nums_size=nums.size();
// Corner case
if(nums_size<2)
return nums_size;
int idx=0;
for(int i=1; i<nums_size; i++)
{
if(nums[idx]!=nums[i])
{
idx++;
nums[idx]=nums[i];
}
}
return idx+1;
}
};