LeetCode 26. Remove Duplicates from Sorted Array && 80. Remove Duplicates from Sorted Array II

9 篇文章 0 订阅
8 篇文章 0 订阅

LeetCode 26. Remove Duplicates from Sorted Array

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 by modifying the input array in-place with O(1) extra memory.

Example:
Given 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.

从有序数组中去重,元素允许的最大重复次数是一次。不允许分配额外的空间制造新的数组,只能直接在原数组上进行修改。在数组中删除某个元素的含义是:将这个元素放到size之外。比如:[1,1,2],就将其变为:[1,2,1]或[1,2,2],然后返回size为2即可。size范围之外的东西,不必考虑,那就等于删除。

这里我使用Two Pointers,cur指向不重复数组的尾部,i用来遍历整个数组,一旦遇到不重项,就将cur+1所指位置赋值为该不重复项。最后返回的结果:不重复数组的长度=cur+1。

    int removeDuplicates(vector<int>& nums) {
        if (nums.size() < 2) return nums.size();
        int cur = 0;
        for (int i = 0; i < nums.size() - 1; i++)
        {
            if (nums[i] != nums[i + 1])
            {
                ++cur;
                nums[cur] = nums[i + 1];
            }
        }
        return cur + 1;
    }

LeetCode 80. Remove Duplicates from Sorted Array II

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 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

这道题是之前那道Remove Duplicates from Sorted Array的扩展,不同的是元素允许的最大重复次数是两次。因此数组[1,1,1,2,2,3]最后保留的是[1,1,2,2,3]。

我根据上一道题的解法,稍作调整。当元素重复了两次后就用一个变量dup记录该元素的值,如果下一个元素和dup相等的话,迭代指针直接向前移动,从下下一个元素开始新一轮比较。

int removeDuplicates(vector<int>& nums) {
        if (nums.size() < 2) return nums.size();
        int dup = nums[0] - 1, cur = 0;
        for (int i = 0; i < nums.size() - 1; i++) {
            if (dup == nums[i + 1]) continue;
            if (nums[i] == nums[i + 1]) dup = nums[i + 1];
            ++cur;
            nums[cur] = nums[i + 1];
        }
        return cur + 1;
    }

更简洁的解法:直接比较当前元素和新数组倒数第二个元素。

int removeDuplicates(vector<int>& nums) {
        int n = nums.size();
        if (n < 3)
            return n;

        int i = 0, newSize = 2;

        for (i = 2; i < n; i++)
        {
            if (nums[i] != nums[newSize-2])
                nums[newSize++] = nums[i];
        }

        return newSize;
    }

更加通用的解法(适用于允许数组元素重复k次):
https://discuss.leetcode.com/topic/7673/share-my-o-n-time-and-o-1-solution-when-duplicates-are-allowed-at-most-k-times

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值