题目大意:给定一个已经排序完成的数组,去除掉其中重复的元素

题目描述

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.

算法描述

由于给定的数组是已经完成排序的数组,所以我们只需要判断第i个元素是否和第i+1个元素相等,就可以知道第i个元素是否是重复的。

另外需要注意的是我们需要将不重复的元素重新放置在数组的前面。

代码

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int cnt = 0, length = nums.size();
        for (int i = 0; i < length; ++i)
            if (i + 1 < length && nums[i] == nums[i + 1]) continue;
            else nums[ cnt++ ] = nums[i];       // 将不重复的元素放置到对应的位置
        return cnt;
    }
};

登录发表评论 注册

反馈意见