Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
What if duplicates are allowed at most twice?
For example,
Given sorted array A =
Given sorted array A =
[1,1,1,2,2,3]
,
Your function should return length =
5
, and A is now [1,1,2,2,3]
.
本来打算装上一下,不过让我上来裸写个version II估计也给跪了。。。不过做过上面一道题,这个就是加个counter的事情,另外,可以在if里面加个循环处理dup k个的情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Solution { public: /** * @param A: a list of integers * @return : return an integer */ int removeDuplicates(vector<int> &nums) { // write your code here if (nums.empty()) return 0; int beg=0; int end=0; int count=1; while(end<nums.size()){ while(end<nums.size()-1 && nums[end]==nums[end+1]){ end++; count++; } nums[beg++]=nums[end]; if (count>1){ nums[beg++]=nums[end]; count=1; } end++; } return beg; } }; |
No comments:
Post a Comment