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

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

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;
    }
};
相关推荐
jiaguangqingpanda29 分钟前
Day24-20260120
java·开发语言·数据结构
52Hz11835 分钟前
力扣24.两两交换链表中的节点、25.K个一组反转链表
算法·leetcode·链表
老鼠只爱大米38 分钟前
LeetCode经典算法面试题 #160:相交链表(双指针法、长度差法等多种方法详细解析)
算法·leetcode·链表·双指针·相交链表·长度差法
ValhallaCoder42 分钟前
Day53-图论
数据结构·python·算法·图论
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #84:柱状图中最大的矩形(单调栈、分治法等四种方法详细解析)
算法·leetcode·动态规划·单调栈·分治法·柱状图最大矩形
C雨后彩虹1 小时前
羊、狼、农夫过河
java·数据结构·算法·华为·面试
Elastic 中国社区官方博客1 小时前
使用瑞士风格哈希表实现更快的 ES|QL 统计
大数据·数据结构·sql·elasticsearch·搜索引擎·全文检索·散列表
重生之后端学习1 小时前
19. 删除链表的倒数第 N 个结点
java·数据结构·算法·leetcode·职场和发展
aini_lovee2 小时前
严格耦合波(RCWA)方法计算麦克斯韦方程数值解的MATLAB实现
数据结构·算法·matlab
安特尼2 小时前
推荐算法手撕集合(持续更新)
人工智能·算法·机器学习·推荐算法