26. Remove Duplicates from Sorted Array

来源:互联网 发布:积分兑换系统源码 编辑:程序博客网 时间:2024/05/14 10:36

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array nums = [1,1,2],

solution:

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int sz = nums.size();        if(sz<=1) return sz;        auto p = nums.begin();        auto c = p+1;        while(c<nums.end()){            if(*p==*c){                c = nums.erase(c);            }            else{                p++;                c++;            }        }        return nums.size();    }};

心得:思路简单,运行速度慢 每次erase 后 nums.end()发生改变

运行速度:慢

0 0
原创粉丝点击