首页 > 其他 > 详细

Remove Duplicates from Sorted Array II

时间:2015-09-29 18:21:52      阅读:235      评论: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.

解题思路:

该题目类似于这个题目, 也是用两个指针,但需要记录变量出现的次数。代码如下:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        size_t n = nums.size();
        if (n <= 2) return n;
        
        size_t i = 2;
        for (size_t j = 2; j < n; ++j) {
            if (nums[j] != nums[i - 2]) {
                nums[i++] = nums[j];
            }
        }
        
        return i;
    }
};

  

 

Remove Duplicates from Sorted Array II

原文:http://www.cnblogs.com/skycore/p/4846935.html

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