本题的解题思路同样是使用快慢指针对数组进行操作,代码如下:
class Solution {
public:int removeDuplicates(vector<int>& nums) {int fastindex = 1;int slowindex = 0;for(fastindex; fastindex < nums.size(); fastindex++){if(nums[fastindex] != nums[slowindex]){nums[++slowindex] = nums[fastindex]; }}return slowindex + 1;}
};
- 最开始尝试用下列条件进行判断,总是出现越界并且数组中覆盖的数的位置出现问题,继而提交失败。
- 应当是后出现的数与前一个数进行判断,如果相等,则用后一个来覆盖前一个
nums[fastindex] != nums[fastindex + 1]
需要对 for 循环判断条件进行修改:
fastindex < nums.size() 修改为 fastindex < nums.size() - 1
class Solution {
public:int removeDuplicates(vector<int>& nums) {int fastindex = 0;int slowindex = 0;for(fastindex; fastindex < nums.size() - 1; fastindex++){if(nums[fastindex] != nums[fastindex + 1]){nums[++slowindex] = nums[fastindex + 1]; }}return slowindex + 1;}
};