LeetCode 80 Remove Duplicates from Sorted Array II

简介: 给定排序的数组nums,就地删除重复项,使重复项最多出现两次并返回新的长度.不要为另一个数组分配额外的空间,必须通过使用O(1)复杂度的额外空间来修改输入数组,从而实现此目的.

v2-ae1864ee17942afd4a03ca79d08f8494_1440w.jpg

Description



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.


Clarification:


Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.


Internally you can think of this:


// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}


描述



给定排序的数组nums,就地删除重复项,使重复项最多出现两次并返回新的长度.

不要为另一个数组分配额外的空间,必须通过使用O(1)复杂度的额外空间来修改输入数组,从而实现此目的.


例1:给定nums = [1,1,1,2,2,3],函数应返回length = 5,其中nums的前五个元素分别为1,1,2,2和3.


数组中超出了你返回范围的值无关紧要.


例2:给定nums = [0,0,1,1,1,1,2,3,3],函数应返回length = 7,nums的前七个元素分别修改为0,0,1,1,2,3和3。


数组中超出了你返回范围的值无关紧要.


对为什么返回值是一个整数但输出的答案是一个数组感到迷惑?


请注意,输入数组通过引用传入,这意味着调用者也将知道对输入数组的修改。

下面这个例子可以帮助你理解:


// nums通过引用传入。 (即没有复制)
int len = removeDuplicates(nums);
//调用者可以知道函数中对nums的任何修改。
//使用函数返回的长度,打印出前len个元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}


思路



  • 这道题我们采用就地移动的方式来是空间复杂度达到O(1).
  • 我们两个变量index,count:index表示已经到达最终位置的元素的后面一个值,count表示当前元素出现的次数.
  • index和count都初始化为1.
  • 如果当前元素等于前面一个元素,count自增一次,如果不等count重置为1.
  • 如果count小于等于2,我们把当前元素放到nums[index],index自增一次.
  • 直到遍历到nums尾部,我们返回index.


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2018-12-22 17:55:43
# @Last Modified by:   何睿
# @Last Modified time: 2018-12-23 10:35:05
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 如果是空则返回0
        if not nums:
            return 0
        index, count = 1, 1
        for i in range(1, len(nums)):
            # 如果两个字符相等
            if nums[i-1] == nums[i]:
                # count计数自增一次
                count += 1
            # 如果不等,count重置为1
            else:
                count = 1
            # 如果count小于等于2,则把nums[i]放到有效位置的后一个位置
            if count <= 2:
                nums[index] = nums[i]
                index += 1
        # 删除无用元素[也可不用删除,LeetCode不会检查后面的元素]
        del nums[index:]
        return index
if __name__ == "__main__":
    nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
    so = Solution()
    res = so.removeDuplicates(nums)
    print(res, nums)


源代码文件在这里.


目录
相关文章
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
225 0
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
237 0
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
259 0
LeetCode 167 Two Sum II - Input array is sorted(输入已排序数组,求其中两个数的和等于给定的数)
给定一个有序数组和一个目标值 找出数组中两个成员,两者之和为目标值,并顺序输出
240 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
算法 测试技术
LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 88. 合并两个有序数组 Merge Sorted Array
|
测试技术 PHP 开发者
PHP 数组查找:为什么 `isset()` 比 `in_array()` 快得多?
PHP 数组查找:为什么 `isset()` 比 `in_array()` 快得多?
|
人工智能 Java
Java 中数组Array和列表List的转换
本文介绍了数组与列表之间的相互转换方法,主要包括三部分:1)使用`Collections.addAll()`方法将数组转为列表,适用于引用类型,效率较高;2)通过`new ArrayList&lt;&gt;()`构造器结合`Arrays.asList()`实现类似功能;3)利用JDK8的`Stream`流式计算,支持基本数据类型数组的转换。此外,还详细讲解了列表转数组的方法,如借助`Stream`实现不同类型数组间的转换,并附带代码示例与执行结果,帮助读者深入理解两种数据结构的互转技巧。
1116 1
Java 中数组Array和列表List的转换
|
存储 Go 索引
go语言中的数组(Array)
go语言中的数组(Array)
435 67

热门文章

最新文章

  • 1
    PHP 数组查找:为什么 `isset()` 比 `in_array()` 快得多?
    369
  • 2
    Java 中数组Array和列表List的转换
    1116
  • 3
    JavaScript中通过array.map()实现数据转换、创建派生数组、异步数据流处理、复杂API请求、DOM操作、搜索和过滤等,array.map()的使用详解(附实际应用代码)
    824
  • 4
    通过array.reduce()实现数据汇总、条件筛选和映射、对象属性的扁平化、转换数据格式、聚合统计、处理树结构数据和性能优化,reduce()的使用详解(附实际应用代码)
    1642
  • 5
    通过array.some()实现权限检查、表单验证、库存管理、内容审查和数据处理;js数组元素检查的方法,some()的使用详解,array.some与array.every的区别(附实际应用代码)
    790
  • 6
    通过array.every()实现数据验证、权限检查和一致性检查;js数组元素检查的方法,every()的使用详解,array.some与array.every的区别(附实际应用代码)
    561
  • 7
    多维数组操作,不要再用遍历循环foreach了!来试试数组展平的小妙招!array.flat()用法与array.flatMap() 用法及二者差异详解
    397
  • 8
    别再用双层遍历循环来做新旧数组对比,寻找新增元素了!使用array.includes和Set来提升代码可读性
    385
  • 9
    Array.forEach实战详解:简化循环与增强代码可读性;Array.forEach怎么用;面对大量数据时怎么提高Array.forEach的性能
    269
  • 10
    深入理解 JavaScript 中的 Array.find() 方法:原理、性能优势与实用案例详解
    897