[leetcode Q26] Remove Duplicates from Sorted Array

来源:互联网 发布:windows邮件客户端 编辑:程序博客网 时间:2024/05/22 18:22

1. 题目要求

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.

不另外申请空间,返回新的数组长度,在原数组中超过新长度的元素可以是任意的。

2. 思路&注意

思路很简单,遍历一遍数组,检查前一个元素与当前元素是否相同,相同则删除当前元素。

  1. 检查输出值
  2. vector erase 函数返回的是指向待删除元素下一个元素的迭代器

3. 实现

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() == 0 || nums.size() == 1)            return nums.size();        vector<int>::iterator i;        vector<int>::iterator j;        for( i = nums.begin() + 1; i < nums.end(); ) {            j = i - 1;            if(*j == *i)                i = nums.erase(i);            else                i++;        }        return nums.size();    }};

测试 AC

0 0
原创粉丝点击