首页 > 代码库 > [LeetCode] Remove Duplicates from Sorted Array

[LeetCode] 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 in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 

发现一道遗留的easy题,说来惭愧,看见这题第一眼就觉得尼玛这不和remove element 一模一样吗,只是这回是要移除重复的,而且对内存有了O(1)的严格限制。同样要求是 in-place 的操作数组,可是我居然忘了当时remove element是怎么做的了。。。相当时我还写出三种解法的啊,怎么现在都想不起来了=_=

仔细回顾了一下之前的博客,终于回想起来了。时间复杂度为O(n) 空间为O(1) 。大体思路就是追踪当前已经删除元素的数量,然后把后面的元素往前移动。

int removeDuplicates(int A[], int n) {    if (n <= 0 ) return 0;    int curdel = 0;    int prev = A[0];    int len = n;    for (int i = 1; i < n; i++) {        int cur = A[i];        if (cur == prev) {            len--;            curdel++;        }else {            if (curdel > 0) {                A[i-curdel] = A[i];            }        }        prev = cur;    }    return len;}

 

[LeetCode] Remove Duplicates from Sorted Array