LeetCode Remove Duplicates from Sorted Array

来源:互联网 发布:单片机公司有哪些 编辑:程序博客网 时间:2024/06/05 06:09

Remove Duplicates from Sorted Array Total Accepted: 52196 Total Submissions: 165553 My Submissions Question Solution
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].

题意:删除有序数组的重复元素

代码一:

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n==0)return 0;        int index=0;        for(int i=1;i<n;++i)        {            if(A[i]!=A[i-1])                A[++index]=A[i];        }        return index+1;    }};

161 / 161 test cases passed.
Status: Accepted
Runtime: 37 ms

代码二(网络获取):

// LeetCode, Remove Duplicates from Sorted Array// 使用STL,时间复杂度O(n),空间复杂度O(1)class Solution {public:int removeDuplicates(int A[], int n) {    return distance(A, unique(A, A + n));    }}

161 / 161 test cases passed.
Status: Accepted
Runtime: 34 ms
在STL中unique函数是一个去重函数, unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。
distance返回两个迭代器之间的距离。

0 0