码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Remove Duplicates from Sorted Array

时间:2014-12-11 01:35:21      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/agentgamer/p/4156662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!