LeetCode: Remove Duplicates from Sorted Array II

来源:互联网 发布:韩国偶像团体 知乎 编辑:程序博客网 时间:2024/04/28 13:07

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

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


Round 2:

class Solution {public:    int removeDuplicates(int A[], int n) {        int l = 0, r = 0, count = 0;while(r < n){if(r-1 >= 0 && A[r] == A[r-1]){count++;if(count <= 1){A[l++] = A[r++];}else{r++;}}else{count = 0;A[l++] = A[r++];}}return l;    }};


0 0
原创粉丝点击