LeetCode---Remove Duplicates from Sorted Array II
2015-08-20 11:29
288 查看
问题是:去掉已排序数组中重复两次超过两次的重复元素,即多于两次的时,保留两次重复元素。然后返回新的数组的大小。并不需要考虑新数组大小后边的元素是什么。
直接上我调试的本地代码。ps:感觉很简单的一道题目,却愁掉了好多根头发,需要加强学习、锻炼啊
大神code:不服不行
直接上我调试的本地代码。ps:感觉很简单的一道题目,却愁掉了好多根头发,需要加强学习、锻炼啊
[code]#include <iostream> #include<vector> #include<stack> using namespace std; /*Problem:Remove Duplicates from Sorted Array II 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. Tags: Array ; Two Pointers */ int removeDuplicates(vector<int>& nums) { int n=nums.size(); if(n==0)return 0; int p=0,q=1; stack<int> sta;sta.push(nums[0]); while(q<n){ if(sta.top()==nums[q]){ if(sta.size()<2){ sta.push(nums[q]); q++; } else{ q++; } } else{ while(!sta.empty()){ nums[p++]=sta.top(); sta.pop(); } sta.push(nums[q]);q++; } } while(!sta.empty()){ nums[p++]=sta.top(); sta.pop(); } return p; } int main() { vector<int>nums={1,1,1,1,2,2,2,3,3,4,5,6,6}; int res=removeDuplicates(nums); for(int i=0;i<nums.size();i++){ cout<<nums[i]<<" "; } cout << "Hello world!" <<res<< endl; return 0; }
大神code:不服不行
[code] int removeDuplicates(vector<int>& nums) { int i = 0; for (int n : nums) if (i < 2 || n > nums[i-2]) nums[i++] = n; return i; }
相关文章推荐
- Codeforces Round #FF (Div. 2) A. DZY Loves Hash
- hdu-4419-Colourful Rectangle-段树区,并寻求
- Input(Checkbox)全选删除
- hdu 1874 畅通工程续-spfa
- python 文件操作
- mybatis逆向工程,自动生成代码
- Git上传代码
- 论复习
- 异常的例子
- ios Mantle使用小记
- Cannot insert the value NULL into column 'StuID', table 'NETRepository.dbo.S
- [STL系列]STL容器性能比较列表
- appium部分api
- HDU 1058 Humble Numbers
- Activity 跳转 以及4中LunchMode
- @Resource注解
- html中的meta标签作用
- /usr/bin/python^M: bad interpreter: No such file or directory
- Spring MVC 的表单标签
- Linux修改MAC地址