LeetCode 80 Remove Duplicates from Sorted Array II

栏目: 编程工具 · 发布时间: 6年前

内容简介:给定一个数组,删除其中的重复元素,使重复项最多出现两次,然后返回新的长度,要求 O(1) 空间复杂度。例 1:例 2:

给定一个数组,删除其中的重复元素,使重复项最多出现两次,然后返回新的长度,要求 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 26 Remove Duplicates from Sorted Array 这道题比较类似。

定义变量 k,表示待修改的元素位置,默认为 0,然后遍历后面的元素判断符合条件时,覆盖 k,然后 k 向后移动一位。

判断条件为:

  • 遍历的元素 n 不等于元素 k,也就代表不重复
  • 遍历的元素 n 等于元素 k,但不等于 k - 1。则表示已经有两个重复元素了
  • 对于第二点,需要注意,当 k = 0 时,没有 k - 1。
class Solution {
    public int removeDuplicates(int[] nums) {
        int k = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] != nums[k] || k == 0 || (nums[i] == nums[k] && nums[i] != nums[k - 1])) {
                nums[++k] = nums[i];
            }
        }
        return k + 1;
    }
}
Runtime: 6 ms, faster than 95.36% of Java online submissions for Remove Duplicates from Sorted Array II.

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms on Strings, Trees and Sequences

Algorithms on Strings, Trees and Sequences

Dan Gusfield / Cambridge University Press / 1997-5-28 / USD 99.99

String algorithms are a traditional area of study in computer science. In recent years their importance has grown dramatically with the huge increase of electronically stored text and of molecular seq......一起来看看 《Algorithms on Strings, Trees and Sequences》 这本书的介绍吧!

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具