删除有序数组中的重复项-力扣

本题的解题思路同样是使用快慢指针对数组进行操作,代码如下:

cpp 复制代码
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;
    }
};
  • 最开始尝试用下列条件进行判断,总是出现越界并且数组中覆盖的数的位置出现问题,继而提交失败。
  • 应当是后出现的数与前一个数进行判断,如果相等,则用后一个来覆盖前一个
cpp 复制代码
nums[fastindex] != nums[fastindex + 1]

需要对 for 循环判断条件进行修改:

cpp 复制代码
fastindex < nums.size() 修改为 fastindex < nums.size() - 1
cpp 复制代码
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;
    }
};
相关推荐
知识浅谈10 分钟前
DeepSeek V4 和 GPT-5.5 在同一天发布了??我也很懵,但对比完我悟了
算法
DeepModel20 分钟前
通俗易懂讲透 Q-Learning:从零学会强化学习核心算法
人工智能·学习·算法·机器学习
田梓燊22 分钟前
力扣:19.删除链表的倒数第 N 个结点
算法·leetcode·链表
简简单单做算法2 小时前
基于GA遗传优化双BP神经网络的时间序列预测算法matlab仿真
神经网络·算法·matlab·时间序列预测·双bp神经网络
阿豪学编程2 小时前
面试题map/unordered相关
数据结构
guygg882 小时前
利用遗传算法解决列车优化运行问题的MATLAB实现
开发语言·算法·matlab
武藤一雄3 小时前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
sali-tec3 小时前
C# 基于OpenCv的视觉工作流-章52-交点查找
图像处理·人工智能·opencv·算法·计算机视觉
梦想的颜色3 小时前
mongoTemplate + Java 增删改查基础介绍
数据结构·数据库·mysql
yu85939583 小时前
MATLAB连续线性化模型预测控制(SL-MPC)
算法·机器学习·matlab