您的位置:首页 > 其它

Leetcode NO.26 Remove Duplicates from Sorted Array

2015-02-11 11:06 218 查看
本题题目要求如下:

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]
.
说来惭愧,本题虽然是一道简单题,但是由于没有看提示two pointer,所以没有想到简单解。。。
我的解法相对比较费时间,是O(nlogn)的时间复杂度,是把重复元素都置为INT_MAX然后最后sort一遍。

不过看到了可以用two pointer解决之后,问题就比较简单了,可以得到O(n)的最优解:

解法就是一个pointer用来遍历数组,另外一个pointer用来指向最后需要得到的数组的元素,直接上代码了,这题怎么讲都不如直接看代码直接:

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


看来刷题还是有用的,现在再看我第一次的O(nlogn)的想法,简直惨不忍睹,现在上传下最新的code吧,跟上面的基本一样,只不过Leetcode的function的argument改了一下。。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.size() == 0) {
            return 0;
        }
        int cnt = 1;
        int tmp = nums[0];
        for (int i = 1; i < nums.size(); ++i) {
            if (nums[i] != tmp) {
                tmp = nums[i];
                nums[cnt++] = nums[i];
            }
        }
        return cnt;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: