[LeetCode] 26.Remove Duplicates from Sorted Array

来源:互联网 发布:金蝶软件服务商 编辑:程序博客网 时间:2024/05/17 04:36

[LeetCode] 26.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 by modifying the input array in-place with O(1) extra memory.

Example:

Given 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.

解题思路

题目的意思是将一个vector中的所有重复元素删除,之后返回新的vector的长度。也是比较简单的,使用vector的erase函数能很容易地解决这个问题,其他的问题就是细节问题了。比如边界的选择以及删除哪一个元素,这些都是要考虑清楚的,不然很容易出问题。还需要注意的是当输入一个空的vector时直接返回0,否则按我的方法会出错。

实验代码

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if (nums.size() == 0) return 0;        for (int i = nums.size()-1; i > 0; i--)            if (nums[i] == nums[i-1])                nums.erase(nums.begin() + i);        return nums.size();    }};