当前位置:网站首页>【leetcode】27.移除元素
【leetcode】27.移除元素
2022-04-22 23:59:00 【liiiiiiiiiiiiike】
题目描述:
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
while(val in nums): # 判断 nums中是否有val
nums.remove(val) #如果存在val就删除val
return len(nums)
python基础知识补充
python List删除元素主要分为以下三种场景:
- 根据目标元素所在位置的索引进行删除,可以使用del关键字或者pop()方法;
del listname[index]
del listname[start:end] #不包括end
listname.pop(index)
listname.pop() # 不写index参数,默认删除列表中的最后一个元素,类似数据结构中的“出栈”操作
#python 并没有push,而是用append
- remove():根据元素值进行删除
注意: remove()方法只会删除第一个和指定值相同的元素,而且必须保证该元素是必须存在的,否则引发ValueError错误
nums.remove(36) # 该操作只会删除一个36,顺序从左到右
- clear():删除列表中所有元素
clear 用来清空列表中所有元素
url.clear()
版权声明
本文为[liiiiiiiiiiiiike]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45074568/article/details/122461178
边栏推荐
- 【事务管理】
- Mysql的字段类型详解
- LabVIEW controls computer shutdown, hibernation, logout and restart
- Character set (de duplication)
- [leetcode] binary tree, 654 largest binary tree, 105 constructs binary tree according to preorder and inorder traversal, 106 constructs binary tree according to inorder and postorder traversal, and 88
- BGP基本配置
- L1-075 obsessive compulsive disorder (10 points)
- (MM-2018)用于行人重识别的局部卷积神经网络
- 力扣习题集1--两数之和
- Thread pool (easy to understand)
猜你喜欢

闭包的实现原理和作用、以及内存泄露

SystemVerilog verification - Test Platform preparation guide learning notes (5): function coverage

重新安装window10

Install the most complete version of ActiveMQ under the official website in 2022 and the official website access method

SystemVerilog verification - Test Platform writing guide learning notes (3): connecting design and test platform

Hypermesh-laminate复合材料案例学习笔记

The implementation principle and function of closure and memory leakage

80386 compilation_ Introduction to global description table GDT

SystemVerilog verification - Test Platform preparation guide learning notes (0): introduction to verification

Visual studio 2019 restore default settings
随机推荐
条件判断(whilec循环&for&switch循环&if-else判断)
Failed to execute goal on project xxxxx
ssh: connect to host 172.31.8.132 port 22: Connection refused
Basic use of redis
【leetcode】二叉树,深入理解前中后序
xpath定位
闭包的实现原理和作用、以及内存泄露
字面量汇整
Day81 (dynamic programming, cross tree traversal)
合并两个有序的数组
简便工作时间的法宝:以密钥验证的方式来登录服务器
3D旋转动画
The implementation principle and function of closure and memory leakage
People's understanding of the industrial Internet is becoming clearer and closer to the industrial Internet
2022-04-22: give you a matrix board with the size of m x n to represent the deck, where each cell can be a warship 'x' or an empty space ', Returns the number of warships placed on the deck board. war
Vscode uses emmylua plug-in to debug unity project tolua code
FPGA (V) one of RTL codes (cross clock domain design)
Project training - Kid zombie
PIL库在深度学习中的常见操作
云计算仿真框架CloudSim介绍(截图版)