给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 你不需要考虑数组中超出新长度后面的元素。
思路:
使用双指针的方法,i,j。i为快指针,j为慢指针。j从0开始,i从1开始。只要nums[i]!=nums[j]。就将当前nums[i]的值赋给此时j的下一位置。最后由于题目上返回数组长度,因此返回++j。
完整代码如下:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0; // 别忘记空数组的判断
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < (nums.size() - 1); fastIndex++) {
if (nums[fastIndex] != nums[fastIndex + 1]) { // 发现和后一个不相同
nums[++slowIndex] = nums[fastIndex + 1]; //slowIndex = 0 的数据一定是不重复的,所以直接 ++slowIndex
}
}
return slowIndex + 1; //别忘了slowIndex是从0开始的,所以返回slowIndex + 1
}
};
int main() {
Solution sol;
vector<int> array = { 0,0,1,1,1,2,2,3,3,4 };
auto out=sol.removeDuplicates(array);
for (int i = 0; i < out; i++) {
cout << array[i] << endl;
}
return 0;
}