leetcode 80 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.

Subscribe to see which companies asked this question.

题意:一个有序数组,每个元素最多出现两次,如果大于两次,把多的去掉,返回去掉后的数组长度len,以及要求数组前len是去掉那些元素之后的元素。//语死早。。看原题好了。。

思路:排序了还不是随便搞? 没要求空间再开一个标记空间。。。O(1)空间的话。。就乱搞一下?

1/* ***********************************************
2Author :111qqz
3Created Time :2017年04月05日 星期三 21时25分48秒
4File Name :80.cpp
5************************************************ */
6class Solution {
public:
 1    int removeDuplicates(vector<int>& nums) {
 2    int siz = nums.size();
 3    if (siz==0) return 0;
 4    int p = 0;
 5    int magic = -324784312;
 6    for ( int i = 0 ; i < siz-1 ; i++)
 7    {
 8        if (nums[i]==nums[i+1]) p++;
 9        else p = 0;
10        if (p>=2) nums[i-1] = magic;
11    }
12    int cur = 0;
13    for ( int i = 0 ; i < siz ; i++)
14    {
15        if (nums[i]!=magic) nums[cur++] = nums[i];
16    }
17    return cur;
    }

};