80. Remove Duplicates from Sorted Array II
来源:互联网 发布:网络编程培训 百度云 编辑:程序博客网 时间:2024/05/22 08:07
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.
Subscribe to see which companies asked this question.
先翻译题目:这道题其实是题26的另一个版本,要求对给定的排序好的数组进行操作,将其中重复超过两次的数字移除,然后返回新数组的长度;
这里相比第26题多加了一个记录重复次数的计数器k,初始化k=0;比较游标i和游标j指向的元素,若重复则k++,否则k归零;
若是游标i与游标j指向的元素相同,则k++,然后查看k的值是否大于或者等于2;若是,则继续j对数组的遍历;
若不是,即k=1,重复了一次,i++,将j指向的数组元素的值赋值给i指向的数组元素;
若是游标i与游标j指向的元素不同,则k归零,然后i++,将j指向的数组元素的值赋值给i指向的数组元素;
最后遍历结束,将i加一,则得到数组的长度;
做该题时发生一个错误是nums.size()的这个括号总是忘了写;
记住别遗漏对空数组的初始判断;
以下为代码示例:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()==0)
return 0;
int i=0;
int j=1;
int k=0;
for(j=1;j<nums.size();j++){
if(nums[i]==nums[j]){
k++;
if(k>=2){
continue;
}
i++;
nums[i]=nums[j];
}
else{
k=0;
i++;
nums[i]=nums[j];
}
}
i++;
return i;
}
};
- 80. Remove Duplicates from Sorted Array II
- 80.Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 80. Remove Duplicates from Sorted Array II
- 前端切图技能总结
- bzoj1922 [Sdoi2010]大陆争霸 有限制最短路
- HashMap源码解析
- 自定义view-使用xml控制界面的呈现
- 2.26
- 80. Remove Duplicates from Sorted Array II
- 【Codeforces Round #402 (Div. 1)】Codeforces 778A String Game
- html5学习--js语句在html文档中的位置
- 配置Eclipse支持JDK8
- Java的基础语法
- 图像拼接与图像分割之实际应用
- 配置方法文件网址
- leetcode 刷题记录
- hdu 5724 Chess(sg博弈)