LeetCode: Remove Duplicates from Sorted Array II

来源:互联网 发布:魔兽世界17173数据库 编辑:程序博客网 时间:2024/06/14 04:27

Remove Duplicates from Sorted Array II
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.

解题过程 :
在leetcode上随机pick的一道题,一道简单题,只需要遍历一遍数组即可,使用迭代器,遍历每个数,定义一个变量length来记录数组长度,初始值为0。 当某个数的前一个数和前前一个数和他相等时,用erase删除这个数,否则length加一。最后返回length的值。代码如下:

   int removeDuplicates(vector<int>& nums) {        vector<int>::iterator iter ;        int length = 0;        for(iter= nums.begin(); iter!= nums.end(); iter++){            if(*iter==*(iter-1) && *iter==*(iter-2) && iter>=(nums.begin()+2)){                iter = nums.erase(iter);                iter--;            }            else length++;        }        return length;    }
0 0
原创粉丝点击