离线下载
PDF版 ePub版

柯于旺 · 更新于 2018-11-28 11:00:43

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

翻译

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

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

例如,
给定输入数组为 [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();
    }
};