首页 > 编程语言 > 详细

LeetCode OJ:Remove Duplicates from Sorted Array II(移除数组中的重复元素II)

时间:2015-10-29 23:22:43      阅读:275      评论:0      收藏:0      [点我收藏+]

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 };

 

LeetCode OJ:Remove Duplicates from Sorted Array II(移除数组中的重复元素II)

原文:http://www.cnblogs.com/-wang-cheng/p/4922080.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!