您的位置:首页 > 职场人生

leetcode之Remove Duplicates from Sorted Array II

2016-02-28 12:40 288 查看
题目:

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.

解答:

很明显的用两个指针和计数来做,用一个指针表示现在正在进行计数的数字,另一个指针表示现在处理的位置

代码很明显如下class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int start = 0;
int end = 1;
int size = nums.size();
if(size <= 2)
return size;
int cnt = 1;
while(end < size)
{
if(nums[start] == nums[end])
{
if(cnt < 2)
{
nums[++start] = nums[end++];
}
else
{
end++;
}
cnt++;
}
else
{
nums[++start] = nums[end++];
cnt = 1;
}
}
return start + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试