<LeetCode OJ> 26 / 80 Remove Duplicates from Sorted Array(I / II)

本文详细介绍了如何使用双指针技术解决LeetCode中关于去除数组重复元素及其变体的问题,包括如何在常数内存下完成操作,并提供了具体的代码实现。此外,还探讨了允许重复元素最多两次的情况下的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

26. Remove Duplicates from Sorted Array


Total Accepted: 104150  Total Submissions: 322188  Difficulty: Easy

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 

It doesn't matter what you leave beyond the new length.




分析:

双指针问题,用len维护当前所有不重复的元素,用i遍历当前元素是否与相邻的元素相等!如果相等什么都不做,如果不相等则修改nums[len++]为当前这个元素。

class Solution {
public:
 int removeDuplicates(vector<int> &nums) {
    if(nums.size() < 2) 
        return nums.size();
    int len = 1;
    for(int i = 1; i < nums.size(); i++){
        if(nums[i] != nums[i - 1])
            nums[len++] = nums[i];
    }
    return len;
    }
};




80. Remove Duplicates from Sorted Array II

Total Accepted: 64365  Total Submissions: 202358  Difficulty: Medium

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3

It doesn't matter what you leave beyond the new length.


分析:

一个道理,双指针,一个指针始终指向当前安全的符合要求的序列,另一个遍历数组

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()<=2)
            return nums.size();
        int len=1,cnt=1;
        for(int j=1;j<nums.size();j++)
        {
            if(nums[j]==nums[j-1])
                cnt++;
            else
                cnt=1;
            if(cnt < 3)
                nums[len++] = nums[j];
        }
        return len;
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/50499722

原作者博客:http://blog.youkuaiyun.com/ebowtang

本博客LeetCode题解索引:http://blog.youkuaiyun.com/ebowtang/article/details/50668895

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值