[LeetCode][Python]27. Remove Element

Given an array and a value, 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 in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3], val = 3

Your function should return length = 2, with the first two elements of nums being 2.

思路:

  1. 使用[:]操作符得到list的copy,遍历list中的元素,如果和target相等,则从原list中删除。此处不能用index来检查,因为在处理过程中会把元素删除,有些元素下标变了,会被漏掉。
    def removeElement2(self, nums, val):
        for ele in nums[:]:
            if ele == val:
                nums.remove(val)
        return len(nums)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,828评论 0 23
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,881评论 18 139
  • 苍绿桂道,匆匆过了多少南方姑娘的身影 青葱如她,何须粉黛,已然醉了谁? 红色的叶子,我想起她扬起的笑 金色的霓裳,...
    山有木希阅读 548评论 9 15
  • 晚风轻吹,偶尔会畅想未来的样子;我微笑着,看到了自己自由的未来。像梦一样的自由,像风一样的自由。蓝天白云下...
    沉迷CEO阅读 304评论 0 0