[leetcode:python]27.Remove Element
来源:互联网 发布:苹果手机如何授权软件 编辑:程序博客网 时间:2024/05/29 17:17
题目:
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.
题意:
给定一个数组和一个值,将数组里所有等于这个值的元素全部移除。
不要分配额外空间给新的数组,空间复杂度为O(1).
数组元素的顺序可以改变。
方法一:性能52ms
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ if len(nums) == 0: return 0 elif val not in nums: return len(nums) else: while val in nums: nums.remove(val) return len(nums)
方法二:性能35ms
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ n = len(nums) i = 0 j = 0 for j in range(0, n): if nums[j] <> val: nums[i] = nums[j] i = i + 1 return i
其中,<>
表示不等于。
0 0
- 27. Remove Element Leetcode Python
- [leetcode:python]27.Remove Element
- Leetcode-Remove element-Python
- 【Leetcode】【python】Remove Element
- 【LeetCode with Python】 Remove Element
- 【LeetCode 27】Remove Element(Python)
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- [Leetcode] 27.Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- Leetcode 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 【LeetCode】27. Remove Element
- leetcode 27. Remove Element
- 网际协议IP(2)之IP地址与硬件地址
- 文章标题HTML5新增特性
- 讯飞开放平台sdk集成之android
- 异常
- searchInsertPlus
- [leetcode:python]27.Remove Element
- 面向对象-(2)
- GFS一致性总结
- Grafana的安装(CentOS )- 千月带你美化监控数据 grafana(1)
- 浅谈js常用内置方法和对象
- windows-caffe下新建项目
- XHR——XMLHttpRequest对象
- bzoj2463: [中山市选2009]谁能赢呢?
- Makefile显示“make: Nothing to be done for xxxx”的解决方法