[leetcode note] Remove Duplicates from Sorted Array II

纵饮孤独 提交于 2019-12-26 11:31:55

时间: 2019-12-25 10:12 PM
题目地址: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

Solution:

public int removeDuplicates(int[] nums) {
    if (null == nums) {
        return 0;
    }
    if (nums.length <= 2) {
        return nums.length;
    }
    int count = 1, position = 1, last = nums[0];
    for (int i = 1; i < nums.length; ++i) {
        if (nums[i] == last) {
            ++count;
        } else {
            count = 1;
        }
        if (count <= 2) {
            nums[position] = nums[i];
            ++position;
        }
        last = nums[i];
    }
    return position;
}

Runtime: 1 ms, faster than 76.07% of Java online submissions for Remove Duplicates from Sorted Array II.
Memory Usage: 37.4 MB, less than 100.00% of Java online submissions for Remove Duplicates from Sorted Array II.

欢迎关注公众号(代码如诗):
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!