Remove Duplicates from Sorted Array II

Medium 原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Remove Duplicates from Sorted Array II

原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

描述

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.

例子

Given nums = [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.

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

Your function should return length =7, with the first five elements of nums being 0,01,1,2,3 and 3 respectively,

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

  • 注意

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.

解法

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

分析:

改进

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int const n=nums.size();
        int index=0;
        for (int i = 0; i < n; ++i) {
            if (i > 0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1]) continue;
                nums[index++] = nums[i];
        }
        return index;
    }
};
class Solution {
public:
    
    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        for (int n : nums)
        if (i < 3 || n > nums[i-3])
            nums[i++] = n;
        return i;
    }
};

总结

最后更新于

这有帮助吗?