26. 删除有序数组中的重复项(参照官方解题思路缩写)
解题思路(仅作个人学习记录,欢迎大佬指正!)
看了官方题解中的解题思路之后写的>>>
1.1 nums.size=0>>>return 0;
1.2 nums.size>0>>>
1.2.1 int slow=1 *slow为慢指针,表示需要确认nums在当前index位置之前是否存在重复的元素值
1.2.2 从index=1开始遍历nums
1.2.2.1 如果当前index的nums元素值不等于前一个index的nums元素值
1.2.2.1.1 说明该索引之前无重复元素,把当前index的元素值覆盖index值为慢指针slow的元素值
1.2.2.1.2 慢指针slow值加1,修改需要需要判断的位置
1.2.3 结束循环,返回slow的值
1.3 end
代码
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0)return 0;
int slow=1;
else{
for(int fast=1;fast<nums.size();++fast){
if(nums[fast]!=nums[fast-1])
nums[slow++]=nums[fast];
}
return slow;}
}
};