LeetCode Remove Duplicates from Sorted Array

来源:互联网 发布:淘宝直播间 编辑:程序博客网 时间:2024/06/12 23:22

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 <= 1) return n;          while(j < n) {              if (A[i] == A[j]) ++j;            else A[++i] = A[j++];        }        return i + 1;}};

第二次刷这个题,两次写的代码都不如上面这种精简(By 三姐)。其实算法很简单,都是一样的。

附:

第一次的代码:

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

第二次的代码:

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


0 0
原创粉丝点击