首页 > 编程语言 > 详细

LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)

时间:2015-11-13 23:39:41      阅读:317      评论:0      收藏:0      [点我收藏+]

翻译

给定一个已排序的数组,删除重复的元素,这样每个元素只出现一次,并且返回新的数组长度。

不允许为另一个数组使用额外的空间,你必须就地以常量空间执行这个操作。

例如,
给定输入数组为 [1,1,2]

你的函数应该返回length = 2, 其前两个元素分别是1和2。它不关心你离开后的新长度。

原文

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) {
        if (nums.begin() == nums.end()) return 0;
        vector<int>::iterator itor;
        for (itor = nums.begin(); itor != nums.end() && itor + 1 != nums.end(); ++itor) {
            while (*itor == *(itor + 1)) {
                nums.erase(itor + 1);
                if (itor + 1 == nums.end())
                    break;
            }
        }
        return nums.size();
    }
};

版权声明:本文为 NoMasp柯于旺 原创文章,未经许可严禁转载!欢迎访问我的博客:http://blog.csdn.net/nomasp

LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)

原文:http://blog.csdn.net/nomasp/article/details/49824675

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