每日一恋 - LeetCode 80. Remove Duplicates from Sorted Array II(删除排序数组中的重复项 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.

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

示例 1:

给定 nums = [1,1,1,2,2,3],

函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。

你不需要考虑数组中超出新长度后面的元素。

示例 2:

给定 nums = [0,0,1,1,1,1,2,3,3],

函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为 0, 0, 1, 1, 2, 3, 3 。

你不需要考虑数组中超出新长度后面的元素。

解题:

这题是每日一恋 - LeetCode 27. Remove Element(删除排序数组中的重复项)的进阶题。

两道题不同点在于,这题是允许有两个重复元素的,然后该题提供的还是有序的数组,所有判断 nums[i] == nums[i-2]是可行的,在题 27 的代码上对判断条件做一下修改就好了。

 public int removeDuplicates(int[] nums) {
    int i = 0;
    for (int n : nums) {
        if (i < 2 || n > nums[i-2])
            nums[i++] = n;
    }
    return i;
}

猜你喜欢

转载自blog.csdn.net/smartnijun/article/details/81562953
今日推荐