Leetcode -- Remove Duplicates from Sorted Array II

来源:互联网 发布:linux 修改密码 编辑:程序博客网 时间:2024/04/25 11:44

https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

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

这一题和Remove Duplicate from Sorted Array其实没有本质的不同,都是依赖快慢指针实现,只是这一题需要再加一个当前数值的计数器,当超过2的时候慢指针就不再前进了。难度不高,时间O(N) 空间O(1)

    public int removeDuplicates(int[] A) {        if(A.length == 0)            return 0;        int curval = A[0];        int cur_counter = 1;        int counter = 1;        for(int i = 1; i < A.length; i++){            if(A[i] == curval){                cur_counter++;                counter = cur_counter <= 2 ? counter + 1 : counter;            }else{                curval = A[i];                counter++;                cur_counter = 1;            }            A[counter - 1] = curval;//虽然每次都在赋值,但实际上当cur_counter > 2的时候counter维持原地,这样写只是为了代码看起来更简洁。        }        return counter;    }


0 0
原创粉丝点击