码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 26 -- Remove Duplicates from Sorted Array

时间:2015-06-10 19:32:23      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:remove

Remove Duplicates from Sorted Array

题目:
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],


题意:
给排序后的字符串去除重复的并且返回去重后的长度。要求不能使用辅助空间。


思路:
定义两个迭代器,相等则erase,不相等cnt++,注意迭代器删除后失效的情况。


代码:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size() == 0){
            return 0;
        }
        if(nums.size() == 1){
            return 1;
        }
        auto iter2 = nums.begin();
        int cnt = 1;
        for(auto iter = nums.begin()+1; iter != nums.end(); ){
            if(*iter2 != *iter){
                cnt++;
                iter2 = iter;
                ++iter;
            }else{
                iter = nums.erase(iter);
            }
        }
        return cnt;
    }
};

leetcode 26 -- Remove Duplicates from Sorted Array

标签:remove

原文地址:http://blog.csdn.net/wwh578867817/article/details/46444645

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!