LeetCode 之 Remove Duplicates from Sorted Array

来源:互联网 发布:相同名字的数据求和 编辑:程序博客网 时间:2024/06/11 09:45

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.

需要注意到:数组是已经排好序的,以及元素最多可以有两个重复。我们可以用两个指针,一个i遍历所有元素,一个index指向新元素或者第3(4,5...)个重复的元素,每次i指向的元素都赋给index指向的元素。最后index的值就是新数组的长度,代码如下:

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int index=0;        int length=nums.size();        for(int i=0;i<length;i++){            if(index<2||nums[i]>nums[index-2])                nums[index++]=nums[i];        }        return index;    }};


0 0
原创粉丝点击