[算法分析与设计] leetcode 每周一题: 80. Remove Duplicates from Sorted Array II

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


题目 :

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.


思路:

本题没什么难度,唯一需要注意的地方是,不但要返回长度length,也要更改数组(因为我直接从·II开始做,

扫描二维码关注公众号,回复: 1827677 查看本文章

没做一,不知道要改,卡了挺久。。。)主要思路就是维护三个状态,一个是计数器count,一个是目前长度

len,一个是对比字id,然后从前往后遍历,当id一样且次数少于2时候,count+1,len+1,同时数组nums[len]

= 字符,当对比字符不一致时候,重置对比字符,count+1,len+1,同时数组nums[len] = 字符, id一样且次

数已经达到2次,不做处理,跳过


代码如下:

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

猜你喜欢

转载自blog.csdn.net/liangtjsky/article/details/78612605