Leetcode:Remove Duplicates from Sorted Array 2

戳我去解题

 

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

 

这个题就在原来的题目基础之上拓展了之下,原来是每个数只能出现1次,现在是至多2次,这时我们只需要用一个变量记录已经出现的次数即可

class Solution {

public:

    int removeDuplicates(int A[], int n) {

        assert(A != NULL && n >= 0);

        if (n == 0) return 0;

        int count = 1;

        int index = 0;

        for (int i = 1; i < n; ++i) {

            if (A[i] != A[index]) {

                A[++index] = A[i];

                count = 1;

            } else {

                if (count < 2) {

                    A[++index] = A[i];

                    ++count;

                }

            }

        }

        return index + 1;

    }

};

count就是记录已经出现的次数,当已经出现的次数小于2时,表示仍然可以再次出现。

注意当A[i] != A[index]时必须把count归1,表示这个数开始计数并且现在出现了1次。

 

拓展:当题目改为至多出现3次? 4次? 这时只需要将count < 2 这个测试语句稍稍修改位对应的即可,题解代码很具有拓展性

你可能感兴趣的:(LeetCode)