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.

Solution 1(C++)

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

Solution 2(C++)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()){
            return 0;
        }
        int n = nums.size();
        int times = 1;
        int cnt = 0;
        for (int i=1;i<nums.size();i++){
            if (nums[i] == nums[i-1]) times++;
            else times = 1;
            if (times > 2){
                nums.erase(nums.begin()+i);
                i--;
                cnt++;
            }
        }
        return n-cnt;
    }
};

Solution 3(C++)

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

算法分析

先说解法二,解法二应该是比较直观的算法,对于这种题我总是卡在如何删除vector中的某一个元素。可以使用函数v.erase()帮助完成。注意解法二中,cnt是删除掉元素的个数,然后for循环中,要不断判断与nums.size()的情况,注意nums.size()是会在erase()之后变化的。

关于解法一就比较有意思了。首先利用以及排好序的特点,如果一个nums[i] > nums[i-2]就说明,有超过2个重复的值出现。

解法二与解法三本质思想相同,但是解法三更加直观。解法三的思路是维护一个count与index。count是统计重复元素出现的次数,如果count > 2那么就跳过。如果< =2,那么就将nums[i]赋值给nums[index],其实如果这里将index换成新的结果数组,含义会更加直观。

还是不是很明白,以后要慢慢体会。

程序分析

关于v.erase()参考:C++——std::Vector

猜你喜欢

转载自blog.csdn.net/zy2317878/article/details/80193989
今日推荐