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.

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

查看所有标签

猜你喜欢:

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

An Introduction to Probability Theory and Its Applications

An Introduction to Probability Theory and Its Applications

William Feller / Wiley / 1991-1-1 / USD 120.00

Major changes in this edition include the substitution of probabilistic arguments for combinatorial artifices, and the addition of new sections on branching processes, Markov chains, and the De Moivre......一起来看看 《An Introduction to Probability Theory and Its Applications》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码