LeetCode OJ:Remove Duplicates from Sorted Array II(移除数组中的重复元素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 1122 and 3. It doesn't matter what you leave beyond the new length.

 
典型的双指针问题,维护两个指针不断更新就可以了,代码如下:

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         int sz = nums.size();
 5         if(!sz) return 0;
 6         int start = 0;//第二个指针
 7         int i = 0;//第一个指针
 8         int count = 0;
 9         int key = nums[0];
10         for(; i < sz; ++i){
11             if(nums[i] == key)
12                 count++;
13             else{
14                 for(int k = 0; k < min(2, count); ++k)
15                     nums[start++] = key;//更改数组元素,指针前移
16                 key = nums[i];
17                 count = 1;
18             }
19         }
20         for(int k = 0; k < min(2, count); ++k)
21             nums[start++] = key;
22         return start;
23     }
24 };

 

posted @ 2015-10-29 22:58  eversliver  阅读(217)  评论(0编辑  收藏  举报