首页 > 其他 > 详细

LeetCode Remove Duplicates from Sorted Array

时间:2015-03-22 18:09:20      阅读:263      评论:0      收藏:0      [点我收藏+]

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返回两个迭代器之间的距离。

LeetCode Remove Duplicates from Sorted Array

原文:http://blog.csdn.net/wdkirchhoff/article/details/44539075

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!