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

来源:互联网 发布:淘宝买的战地1激活码 编辑:程序博客网 时间:2024/05/20 05:44

题目链接: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开始做,

没做一,不知道要改,卡了挺久。。。)主要思路就是维护三个状态,一个是计数器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;            }};

阅读全文
0 0
原创粉丝点击