leetcode 26 Remove Duplicates

来源:互联网 发布:发现你修改了mac地址 编辑:程序博客网 时间:2024/05/21 09:43

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],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

class Solution {public:    int removeDuplicates(vector<int>& nums) {        list<int> list(nums.begin(), nums.end());        typedef std::list<int>::iterator iter;        iter b = list.begin();        cout << *b <<endl;        iter e  = list.begin();        while (e != list.end()) {            if (*e != *b){                    e = list.erase(++b, e);                b = e;            } else {                ++e;            }        }        list.erase(++b, e);        nums = vector<int>(list.begin(), list.end());        cout << list.size();        return list.size();    }}; // runtime contribution 32% 

参考后

class Solution {public:    int removeDuplicates(vector<int>& nums) {        typedef vector<int>::size_type sz;        sz size = nums.size();        if (size <= 1) return size;        int count = 0;        for (sz i = 1; i < size; ++i){            if (nums[i - 1] == nums[i]) ++count;            else                nums[i - count] = nums[i];        }        nums.erase(nums.begin() + (size - count), nums.end());        return size - count;    }}; // runtime contribution 91.2%
阅读全文
0 0
原创粉丝点击