80. Remove Duplicates from Sorted Array II拓展成最多重复K个的巧妙解法

在做LeetCode上的第80道题时,自己做出来了,但觉得自己的方法不是最优的方法,看了一下论坛,被点赞最多的解法给惊呆了,记录一下这种巧妙的解法,同时将最多重复2个拓展成最多重复K个。
原题题目:

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice 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 1:
Given 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 respectively.
It doesn’t matter what you leave beyond the returned length.

自己的解法为:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
       if(nums.size() < 2)
        return nums.size();
    size_t k = 0, count = 1;
    for(size_t i = 1; i < nums.size(); i++){
        if(nums[i] == nums[k] && count < 2){
            nums[++k] = nums[i];
            count++;
        }
        else if(nums[i] != nums[k]){
            nums[++k] = nums[i];
            count = 1;
        }
    }
    return k+1;
    }
};

点赞最高的解法为:

int removeDuplicates(vector<int>& nums) {
    int i = 0;
    for (int n : nums)
        if (i < 2 || n > nums[i-2])
            nums[i++] = n;
    return i;
}

这里利用了已经排序好的数组的特性。
可以利用该作者的思路进行拓展成最多重复K个,代码实现如下:

int removeDuplicatesK(vector<int> &nums, int k){
    int i = 0;
    for(int num : nums){
        if(i < k || num > nums[i - k])
            nums[i++] = num;
    }
    return i;
}

以后在遇到类似问题时,可以参考这个解决方案,其中k变为1,或者2时是两种不同的LeetCode上面的题目,但是解决方法可以都用这种方案。

希望大家在LeetCode上刷题时,不要仅仅把题目做出来就停止了,可以看看讨论区中点赞量最高的人的答案,学习参考一下。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值