leetcode刷题,总结,记录,备忘 80

leetcode80 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 1122 and 3. It doesn't matter what you leave beyond the new length.

Subscribe to see which companies asked this question

题目要求是最多保留2个相同,第三个删掉。这里我灵机一动,想了个绝妙的方法。使用2个set容器,在遍历数组的时候,根据奇偶次数,分别往2个不同的set容器里插入数值,保证每个相同的只有2个数会被成功插入,如果有第三个就会插入失败,此时删掉他,最后返回2个set容器的长度和即可。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        set<int> s1;
        set<int> s2;
        
        for (int i = 0; i < nums.size(); ++i)
        {
            pair<set<int>::iterator, bool> p;
            if (i % 2 == 0)
            {
                p = s1.insert(nums[i]);
                if (p.second == false)
                {
                    nums.erase(nums.begin() + i);
                    i--;
                }
            }
            else
            {
                p = s2.insert(nums[i]);
                if (p.second == false)
                {
                    nums.erase(nums.begin() + i);
                    i--;
                }
            }
        }
        
        return s1.size() + s2.size();
    }
};


你可能感兴趣的:(leetcode刷题,总结,记录,备忘 80)