[leetcode] 80. 删除排序数组中的重复项 II

80. 删除排序数组中的重复项 II

模拟,没啥意思。。就是挪数而已

class Solution {
    public int removeDuplicates(int[] nums) {
        int cnt = 0;
        int len = nums.length;
        int top = 0;
        int last = Integer.MAX_VALUE;
        while (len > 0) {
            len--;
            if (nums[top] == last) {
                cnt++;
                if (cnt > 2) {
                    int k = top;

                    while (k < nums.length && nums[k] == nums[top]) {
                        k++;
                        len--;
                    }
                    if (k >= nums.length) break;
                    move(nums, top, k);
                    cnt = 1;
                    last = nums[top];
                }
            } else {
                cnt = 1;
                last = nums[top];
            }
            if (len < 0) break;
            top++;
        }
        return top;
    }

    private void move(int[] nums, int top, int k) {
        for (int i = 0; i + k < nums.length; i++) {
            nums[i + top] = nums[i + k];
        }
    }

}
posted @ 2018-07-30 16:38 ACBingo 阅读(...) 评论(...) 编辑 收藏