当前位置:网站首页>leetcode 27:移除元素
leetcode 27:移除元素
2022-08-10 03:16:00 【Rolandxxx】
题目描述:给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素
示例:
输入:nums = [0,1,2,2,3,0,4,2], val = 2
输出:5, nums = [0,1,4,0,3]
我的解法:这道题目和移动0十分类似,所以解法可以套用
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if nums is None or len(nums)==0:
return 0
index = 0
for num in nums:
if num != val:
nums[index] = num
index +=1
return index
双指针解法:
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
if nums is None or len(nums)==0:
return 0
left = 0
right = len(nums)-1
while left<right:
while left<right and nums[left]!=val:
left+=1
while left<right and nums[right] == val:
right -=1
tmp = nums[left]
nums[left] = nums[right]
nums[right] = tmp
if nums[left] == val:
return left
else:
return left+1
边栏推荐
- C - The Battle of Chibi (dp加树状数组前缀和优化)
- 带你深入理解3.4.2的版本更新,对用户带来了什么?
- cuda——nms
- Example 047: Functions Swap Variables
- flutter 每天一背,需要掌握
- yolov5+usb相机
- 当我操作dms客户端的时候,我要操控好几个阿里云账号下的数据库,但是这边每次切换都会把我的登录记录删
- day17正则表达式作业
- golang:base64编解码(转)
- Take you to an in-depth understanding of the version update of 3.4.2, what does it bring to users?
猜你喜欢

如何让导电滑环信号更好

从8k到13k,我全靠这本《接口自动化测试——从入门到精通》

Small program subcontracting and subcontracting pre-download

How to write a high-quality test case?

动态网页开发基础

互联网公司高频面试题精讲:测试计划和测试方案有什么区别?

Little rookie Hebei Unicom induction training essay

How to quickly become a software test engineer?What skills do testers need for a monthly salary of 15k?

exchange2010 邮件数据库无法装入

快35了,还在“点点点”?那些入行几年的测试点工后来都怎么样了?
随机推荐
怎么进行服务器性能监控,有什么监控工具
Take you to an in-depth understanding of the version update of 3.4.2, what does it bring to users?
Neo4J 与 Cypher 查询语言基础
金融财经翻译的行业前景如何
盘式导电滑环的优点和缺点
Little rookie Hebei Unicom induction training essay
10个超赞的C语言开源项目,值得学习
No ‘Access-Control-Allow-Origin‘ header is present on the requested resource.
Arrays类
【IO复用】poll
量化投资学习——在FPGA上运行高频交易策略
请教各位confluence部署连接数据库成功,但是在后面建表设置的时候报错
笔试题记录
全面深入了解什么是反向代理和负载均衡
【Image Classification】2022-ConvMixer ICLR
Example 047: Functions Swap Variables
matlab simulink response spectrum calculation
The same is a primary test, why does he pay 5,000 yuan more than me?
带你深入理解3.4.2的版本更新,对用户带来了什么?
过水滑环的结构和工作原理