LeetCode_26

题目描述:

Given a sorted array nums, 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.

解题思路:

要求删除数组中的重复元素。

定义好 [0,k)范围内为非重复元素。 定义一个变量pre记录上一个元素的值,且仅当下一个元素的值不等于pre时再更新。

代码如下:

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

 

posted on 2019-03-09 17:09  harchar  阅读(98)  评论(0)    收藏  举报

导航