题目描述:
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.
例子:
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.
分析:
题意:给定一个有序数组,移除重复元素,使得每种元素只出现一次,并且返回新的数组长度。空间复杂度要求为O(1)。
思路:此题采用双指针法。我们先初始化指针left=0、right=1,并且用cnt表示每个不重复元素在数组中的新位置,初始化为1。我们先查找第一个和指针left指向元素不同的元素位置,用指针right指向它,更新该元素到cnt位置,cnt加一,然后继续重复该操作(把指针right的值赋给指针left,指针right加一),直到更新完成所有元素。cnt的最终值就是新数组的长度。
假设原数组总共有n个元素,那么时间复杂度为O(n),空间复杂度为O(1)。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
// Exceptional Case:
if(n <= 1){
return n;
}
int left = 0, right = 1, cnt = 1;
while(right <= n - 1){
while(right <= n - 1 && nums[left] == nums[right]){
right++;
}
if(right <= n - 1){
nums[cnt++] = nums[right];
left = right;
right = left + 1;
}
}
return cnt;
}
};