[leetcode] 80. Remove Duplicates from Sorted Array II

Description

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.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

分析

题目的意思是:给定一个数组,如果数字出现频率超过两次,就保留两次,把剩下的移除,然后返回移除数字之后的数组的长度。

C++实现

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int m=nums.size();
        if(m<=2){
            return m;
        }
        int pre=0;
        int cur=1;
        int count=1;
        while(cur<m){
            if(nums[cur]==nums[pre]&&count==0){
                cur++;
            }else{
                if(nums[cur]==nums[pre]){
                    count--;
                }else{
                    count=1;
                }
                pre++;
                nums[pre]=nums[cur];
                cur++;
            }
        }
       return pre+1;
    }
};

Python实现

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        n = len(nums)
        if n<2:
            return n

        slow = 2
        fast = 2
        while fast<n:
            if nums[slow-2]!=nums[fast]:
                nums[slow]=nums[fast]
                slow+=1
            fast+=1
        return slow

参考文献

[编程题]remove-duplicates-from-sorted-array-ii
[LeetCode] Remove Duplicates from Sorted Array II 有序数组中去除重复项之二

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值