Leetcode NO.26 Remove Duplicates from Sorted Array

来源:互联网 发布:excel数据比对怎么做 编辑:程序博客网 时间:2024/05/22 07:46

本题题目要求如下:

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;    }};

再上传一个更为简洁的版本:

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int id = 1;        for (int i = 1; i < nums.size(); ++i) {            if (nums[i] != nums[i-1]) {                nums[id++] = nums[i];            }        }        return min(static_cast<int>(nums.size()), id);    }};




0 0
原创粉丝点击