LeetCode OJ:Remove Duplicates from Sorted Array

来源:互联网 发布:2016淘宝做什么产品好 编辑:程序博客网 时间:2024/06/06 07:44

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].

算法思想:

数组循环前移会超时,所以利用一辅助数组B去除不需要的元素,时间复杂度O(n),空间复杂度O(n)

class Solution {public:    int removeDuplicates(int A[], int n) {        if(n==0)return 0;        vector<bool> B(n,false);        for(int i=1;i<n;i++)            if(A[i]==A[i-1])                B[i]=true;        int count=0;        for(int i=0;i<n;i++){            if(!B[i])A[count++]=A[i];        }        return count;    }};

answer2

时间复杂度O(n),,空间复杂度O(1)

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


answer3

时间复杂度O(n),空间复杂度O(1)

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

answer4

时间复杂度O(n),空间复杂度O(1)

class Solution {public:    int removeDuplicates(int A[], int n) {        int *first=A,*last=A+n,*cur=A;        while(first!=last){            *cur++=*first;            first=upper_bound(first,last,*first);        }        return cur-A;    }};


0 0
原创粉丝点击