关关的刷题日记09——Leetcode 80. Remove Duplicates from Sorted Array II

时间:2022-05-07
本文章向大家介绍关关的刷题日记09——Leetcode 80. Remove Duplicates from Sorted Array II,主要内容包括关小刷刷题09 – Leetcode 80. Remove Duplicates from Sorted Array II 方法1、2、思路、方法1、方法2、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

关小刷刷题09 – Leetcode 80. Remove Duplicates from Sorted Array II 方法1、2

题目

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.

思路

与26. Remove Duplicates from Sorted Array的差别是,这次数组的元素可以出现一次或者两次,超过两次的要删掉。26题中的思路1是没法用了,思路2和思路3还是可以继续用的。

方法1

方法1:时间复杂度O(n2)

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

方法2

方法2:时间复杂度O(n): 这个改进版本为什么不能把26题中的i-1直接改成i-2呢?如果要是直接这样改的话,看一下这个例子: 1 1 1 2 2 3 4,当处理到nums[3]的时候,把2存到数组前面,数组变成 1 1 2 2 2 3 4,这个时候再处理nums[4]结果就错了。所以呢,我们还是得相邻元素作比较,要设置一个flag变量标记下,保证元素数目不要超过2. 当前后元素相等的时候,看一下flag如果是1说明前面只有一个该元素,此时将flag置为2,把该元素再存入数组前面,如果flag是2说明前面至少有两个该元素,就什么都不做。如果前后元素不相等的情况下,直接将flag置为1开始重新计数,并且把该元素存入数组前面。

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

不拼搏,枉少年,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。