[Leetcode] Remove Duplicates from Sorted Array II

来源:互联网 发布:阿里云计算机有限公司 编辑:程序博客网 时间:2024/06/03 22:38

题目:

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


思路:双指针,设置一个flag,可以重复一次。

class Solution {public:    int removeDuplicates(int A[], int n) {        if (n <= 0) return n;        int runner = 0;        bool allow_dup = true;        for (int i = 1; i < n; ++i) {            if (A[i] == A[runner]) {                if (allow_dup) {                    A[++runner] = A[i];                    allow_dup = false;                }            } else {                allow_dup = true;                A[++runner] = A[i];            }        }        return runner + 1;    }};


总结:复杂度为O(n). 

0 0
原创粉丝点击