leetcode解题报告(1):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].

分析

要去掉有序数组中的重复数字,需要设置一个索引index,该索引初始化为第一个元素下标,用于与后续数组元素比较。若相等,则跳过,否则,将index下标加1,并使当前比较的元素的下标等于该索引值,直到最后一个元素。由于index为数组下标值,因此将其加1后才是数组长度。

解该题的思想为:将所有检查到的不重复的元素的下标改为一段连续的数值以作为新的下标。

以题述为例:index初始化为0,即A[0],将其与第二个元素A[1]比较,相同,跳过;再与第三个元素A[2]比较,不同,则将index加1,即以A[++index](此时index的值为1)作为元素A[2]的新下标。然后发现数组遍历已结束,退出。至此,就得到了一个不重复的有序数组。

该解法的时间复杂度为O(n),空间复杂度为O(1)

代码如下:

class Solution{
public:
    int removeDuplicates(int A[],int n){
        int index = 0;  
        for(int i = 1; i != n; ++i){    //Note:the for loop begins from the second  element in the array
            if(A[index] != A[i])    //if not equal
                A[++index] = A[i];  //modify index of the original elements
            //if equal,do nothing(which means not changing the value of index)
        }
    }
    return index + 1;   //the result is index plus 1
}

使用STL

如果使用STL,可以考虑distanceunique这两个函数。

distance函数接受两个迭代器参数,该函数返回两个迭代器之间的距离(即长度);

unique函数同样接受两个迭代器参数,该函数去除迭代器范围内的重复元素,并返回最后一个元素的尾后指针。

使用这两个算法的代码如下:

class Solution{
public:
    int removeDuplicates(int A[],int n){
        return distance(A,unique(A,A + n));
    }
}

该解法的时间复杂度为O(n),空间复杂度为O(1)

posted @ 2017-04-20 19:10  larryking  阅读(186)  评论(0编辑  收藏  举报