[array] leetCode-26. Remove Duplicates from Sorted Array - Easy

26. Remove Duplicates from Sorted Array – Easy

descrition

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.

解析

注意题目的要求,in_place,即原址,不能借助额外的辅助空间。
再关注到另一个有利的前提条件,数组是有序的,因此重复的数字一定挨着,这是达到最优解的关键,时间复杂度 O(n)。

code


#include <vector>
#include <algorithm>

using namespace std;

class Solution{
public:
    int removeDuplicates(vector<int>& nums){
        if(nums.empty()) // don't forget the special case!!!!
            return 0;

        int cur = 0; // the end of new nums
        for(int i=1; i<nums.size(); i++){
            if(nums[i] != nums[cur]){
                nums[++cur] = nums[i];
            }
        }

        return cur+1; // return the new length
    }
};

int main()
{
    return 0;
}

作者:fanling999 链接:https://www.cnblogs.com/fanling999/

    原文作者:fanling999
    原文地址: https://www.cnblogs.com/fanling999/p/7828895.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞