vector 容器

来源:互联网 发布:跑步后的拉伸运动知乎 编辑:程序博客网 时间:2024/06/16 15:26

Remove Duplicates from Sorted Array

Description
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.
Translation
给出一个有序的数组,删除数组中重复的元素使得每个元素只出现以此,并且返回数组新的长度。
不能够额外定义一个数组空间,只能在原来的数组上进行操作。
Solution

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int count = nums.size();        if (count< 2)return count;        int temp = nums[0];        vector<int>::iterator iter = nums.begin();        iter++;        for (; iter != nums.end();){            if (temp != (*iter)){ temp = (*iter); iter++; }            else {                iter=nums.erase(iter);                count--;            }        }        return count;    }};

注:利用迭代器访问vector容器,并调用erase方法删除迭代器所指向的元素,返回当前迭代器指向的下一个元素。这里如果打算使用iter++或者采用另起一个变量方法,在调用erase 方法后达到保留指向的目的,会出现runtime error 的错误。