您的位置:首页 > 其它

LeetCode---Remove Duplicates from Sorted Array II

2015-08-20 11:29 288 查看
问题是:去掉已排序数组中重复两次超过两次的重复元素,即多于两次的时,保留两次重复元素。然后返回新的数组的大小。并不需要考虑新数组大小后边的元素是什么。

直接上我调试的本地代码。ps:感觉很简单的一道题目,却愁掉了好多根头发,需要加强学习、锻炼啊

[code]#include <iostream>
#include<vector>
#include<stack>
using namespace std;
/*Problem: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.

Tags: Array ; Two Pointers

*/
    int removeDuplicates(vector<int>& nums) {
        int n=nums.size();
        if(n==0)return 0;
        int p=0,q=1;
        stack<int> sta;sta.push(nums[0]);
        while(q<n){
            if(sta.top()==nums[q]){
                if(sta.size()<2){
                    sta.push(nums[q]);
                    q++;
                }
                else{
                    q++;
                }
            }
            else{
                while(!sta.empty()){
                    nums[p++]=sta.top();
                    sta.pop();
                }
                sta.push(nums[q]);q++;
            }
        }
        while(!sta.empty()){
            nums[p++]=sta.top();
            sta.pop();
        }
        return p;
    }
int main()
{
    vector<int>nums={1,1,1,1,2,2,2,3,3,4,5,6,6};
    int res=removeDuplicates(nums);
    for(int i=0;i<nums.size();i++){
        cout<<nums[i]<<" ";
    }
    cout << "Hello world!" <<res<< endl;
    return 0;
}




大神code:不服不行

[code]    int removeDuplicates(vector<int>& nums) {
    int i = 0;
    for (int n : nums)
        if (i < 2 || n > nums[i-2])
            nums[i++] = n;
    return i;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: