首页 > 其他 > 详细

leetcode 26 -- Remove Duplicates from Sorted Array

时间:2015-06-10 19:30:54      阅读:140      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!