您的位置:首页 > 其它

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

2017-11-23 11:30 387 查看
题目链接: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 
1
1
2
2
 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
4000
(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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: