80. Remove Duplicates from Sorted Array II
2017-02-10 21:29
393 查看
problem:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums =
Your function should return length =
It doesn't matter what you leave beyond the new length.
思路是只保存最后两个重复的元素,所以对nums进行循环,若和两位后的数据不一样,则保存下来,否者不操作。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int result=0;
if(nums.size() < 3)
return nums.size();
vector<int> temp;
for(int i=0; i<nums.size()-2; i++)
{
if(nums[i] != nums[i+2])
{
temp.push_back(nums[i]);
result++;
}
}
temp.push_back(nums[nums.size()-2]);
temp.push_back(nums[nums.size()-1]);
nums = temp;
return result+2;
}
};
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,
2and
3.
It doesn't matter what you leave beyond the new length.
思路是只保存最后两个重复的元素,所以对nums进行循环,若和两位后的数据不一样,则保存下来,否者不操作。
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int result=0;
if(nums.size() < 3)
return nums.size();
vector<int> temp;
for(int i=0; i<nums.size()-2; i++)
{
if(nums[i] != nums[i+2])
{
temp.push_back(nums[i]);
result++;
}
}
temp.push_back(nums[nums.size()-2]);
temp.push_back(nums[nums.size()-1]);
nums = temp;
return result+2;
}
};
相关文章推荐
- UVA 1349 Optimal Bus Route Design(最小权完美匹配)
- 1060. 爱丁顿数(25)
- 关于SoftHashMap实现相关内容
- 对称加密与非对称加密
- CSU-1640
- 面试题3
- ROC曲线及其matlab实现ROC曲线的绘画
- android入门之服务
- 树莓派+Python+pyserial 2.7实现串口通信
- JZOJ-senior-3502. 【NOIP2013模拟11.4B组】方格游戏
- 1059. C语言竞赛(20)
- Opencv 3.1安装遇到的问题记录
- ArcGIS api for js三种查询方法比较
- CSU-1639
- CPU问题定位与解决
- sdut acm 插入排序
- git——萌新学git(1)
- P1217 [USACO1.5]回文质数 Prime Palindromes
- 五种开源协议的比较(BSD,Apache,GPL,LGPL,MIT)
- iOS中NSFileManager文件常用操作整合