Remove Duplicates from Sorted Array II--LeetCode

来源:互联网 发布:淘宝网店流量 编辑:程序博客网 时间:2024/05/20 05:25

1.题目

Remove Duplicates from Sorted Array II

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.

2.题意

在Remove Duplicates from Sorted Array 的基础上,允许每个元素重复出现两次

3.分析

1)在[2, len)范围内遍历数组
将nums[i]与nums[index - 2]作比较
若不相等,则将nums[i]放回原数组,达到去重的目的
这种解法可以拓展应用于这一类问题
2)在[1, len)范围内遍历数组
判断是否出现3个相同的数

4.代码

1)

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

2)

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