码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode80 Remove Duplicates from Sorted Array II

时间:2016-09-30 01:38:56      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice? (Medium)

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.

分析:

仍然采用Remove Duplicates from Sorted Array I 中的双指针思路,只不过增加一个变量count记录出现的次数,两次以内的仍然可以添加的数组中。

代码:

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         if (nums.size() == 0) {
 5             return 0;
 6         }
 7         int count = 0, p = 1;
 8         for (int i = 1; i < nums.size(); ++i) {
 9             if (nums[i] == nums[i - 1]) {
10                 if (count < 1) {
11                     nums[p] = nums[i];
12                     p++;
13                 }
14                 count++;
15             }
16             else {
17                 nums[p] = nums[i];
18                 p++;
19                 count = 0;
20             }
21         }
22         return p;
23     }
24 };

 

 

LeetCode80 Remove Duplicates from Sorted Array II

标签:

原文地址:http://www.cnblogs.com/wangxiaobao/p/5922168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!