您的位置:首页 > 其它

LeetCode: Remove Duplicates from Sorted Array II

2014-04-02 00:00 477 查看
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]
加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解决。如果是没有排序的数组,则需要引入一个 hashmap 来记录出现次数。

方法一

// LeetCode, Remove Duplicates from Sorted Array II
// 时间复杂度 O(n),空间复杂度 O(1)
class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            if (n <= 2) return n;
            int index = 2;
            for (int i = 2; i < n; i++){
                if (A[i] != A[index - 2])
                    A[index++] = A[i];
            }
            return index;
        }
};

方法二

// LeetCode, Remove Duplicates from Sorted Array II
// 时间复杂度 O(n),空间复杂度 O(1)
class Solution {
    public:
        int removeDuplicates(int A[], int n) {
            int index = 0;
            for (int i = 0; i < n; ++i) {                 
                if (i > 0 && i < n - 1 && A[i] == A[i - 1] && A[i] == A[i + 1])
                    continue;
                A[index++] = A[i];
            }
            return index;
        }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: