80. Remove Duplicates from Sorted Array II
2016-06-09 21:42
218 查看
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?
For example,
Given sorted array nums =
Your function should return length =
Analysis:
II和I没有太大区别,加个计数变量即可。
Source Code(C++):
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.
Analysis:
II和I没有太大区别,加个计数变量即可。
Source Code(C++):
#include <iostream> #include <vector> #include <map> using namespace std; class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.empty()) { return 0; } if (nums.size() == 1){ return 1; } int index=0; int count=1; for (int i=1; i<nums.size(); i++){ if (nums.at(i)!=nums.at(index)){ index++; nums.at(index)=nums.at(i); count=1; } else if (nums.at(i)==nums.at(index) && count<2) { count++; index++; nums.at(index)=nums.at(i); } } return index+1; } }; int main() { vector<int> v; v.push_back(1);v.push_back(1);v.push_back(1);v.push_back(2);v.push_back(2);v.push_back(3); Solution sol; cout << sol.removeDuplicates(v) << endl; return 0; }
相关文章推荐
- 初试scrapy编写twitter爬虫
- 二叉排序树 字典树 树中统计
- 关于初学者上传文件到github的方法
- css块级元素、内联元素
- jquery实现井字格游戏
- [线性常微分方程][1] 线性系统与线性理论基础LINEAR SYSTEMS AND THE LINEARITY PRINCIPLE
- 从今天开始写写微博,分享技术,记录进步
- cannot open file "mfc42u.lib"解决办法!
- 用macports装了一份openssl
- Jetbrains phpstorm pycharm 免费授权注册码
- centOS6.4安装桌面
- Jetbrains phpstorm pycharm 免费授权注册码
- Android AIDL的总结与介绍
- Thailand vs Soros
- 《剑指offer》:[28]字符串的全排列问题
- C语言基础-函数getchar和函数scanf小结
- VB模拟出的按键精灵大部分功能
- POJ 2154 Color(Polya原理+欧拉函数)
- Zephyr 教程:源码结构
- 链表的逆置