[Leetcode] Remove Duplicates from Sorted Array II

来源:互联网 发布:广东广电网络营业厅 编辑:程序博客网 时间:2024/04/30 17:18

描述

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 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

给定一个有序数组,将重复的元素去掉,要求同一个值最多可以重复两次。

分析

这道题是 Remove Duplicates from Sorted Array 的升级版,增加了一个条件是每个值最多可以出现两次。

和原来的意思一致,使用双指针的方法遍历数组,当满足下面两种情况之一时,将当前的值储存到新数组中。
1. 当前值与新数组最后一个值不同;
2. 当前值与新数组最后一个值相同,但这个值在新数组中只出现了一次。

代码

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

相关问题

Remove Duplicates from Sorted Array

0 0
原创粉丝点击