LeetCode 27. Remove Element

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

内容简介:Given an arrayDo not allocate extra space for another array, you must do this byThe order of elements can be changed. It doesn’t matter what you leave beyond the new length.
  • 英文:

Given an array nums and a value val , remove all instances of that value in-place 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.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

  • 中文:

给定一个数组 nums 和一个值 val ,你需要 原地 移除所有数值等于 val 的元素,返回移除后数组的新长度。

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

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

示例

  • 示例 1:
给定 nums = [3,2,2,3], val = 3,

函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。

你不需要考虑数组中超出新长度后面的元素。
  • 示例 2:
给定 nums = [0,1,2,2,3,0,4,2], val = 2,

函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。

注意这五个元素可为任意顺序。

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

题解

  • 题解 1

使用两个游标 i 和 j 来遍历数组,如果 第 i 个元素的值等于 val,则使用 j 记录位置,同时递增 i,直到下一个不等于 val 的元素出现,将此时 i 对应的值复制到 j 的位置上,再增加 j ,重复上述过程直到遍历结束。最后,j 就是新数组的长度。

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        j = 0
        for i in range(len(nums)):  # 遍历数组
            if nums[i] != val:  # 不等于时才记录
                nums[j] = nums[i]  # 复制不等于 val 的值
                j += 1  # 新数组的长度
        return j
  • 题解 2

使用列表的 pop() 方法:

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        while val in nums:  # 如果列表中还有目标元素
            nums.pop(nums.index(val))  # 移除该元素
        return len(nums)
  • 题解 3

使用 del 语句:

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        while val in nums:  # 如果列表中还有目标元素
            del nums[nums.index(val)]  # 移除该元素
        return len(nums)
  • 题解 4

使用列表的 remove() 方法(此方法效率最高):

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        while val in nums:  # 如果列表中还有目标元素
            nums.remove(val)  # 移除该元素
        return len(nums)

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

查看所有标签

猜你喜欢:

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

总开关

总开关

[美] 吴修铭 / 顾佳 / 中信出版社 / 2011-8 / 49.00元

当收音机经历从真空管收音机到半导体收音机,再到电晶体收音机的发展升级时,人们觉得自己的资讯来源美满得无可复加了。当约翰.洛吉.贝尔德发明了电视以后,在很长一段时间内,人们都认为电视就是他们所拥有的﹑也是所愿意拥有的最好的资讯媒介。 时至今日,互联网的震撼不亚于以往任何媒介,它给我们带来了最大的信息量,最便捷的自我表达,最迅速的沟通。互联网似乎比以往任何媒介都具有优越性。在互联网成为这个时代主......一起来看看 《总开关》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器