当前位置:网站首页>27. 移除元素
27. 移除元素
2022-06-25 06:41:00 【AlbertOS】
引入
给你一个数组 n u m s nums nums 和一个值 v a l val val,你需要 原地 移除所有数值等于 v a l val val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O ( 1 ) O(1) O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
示例
输入:nums = [3,2,2,3], val = 3
输出:2, nums = [2,2]
解释:函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。你不需要考虑数组中超出新长度后面的元素。例如,函数返回的新长度为 2 ,而 nums = [2,2,3,3] 或 nums = [2,2,0,0],也会被视作正确答案。
输入:nums = [0,1,2,2,3,0,4,2], val = 2
输出:5, nums = [0,1,4,0,3]
解释:函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。注意这五个元素可为任意顺序。你不需要考虑数组中超出新长度后面的元素。
题解
这个用双指针覆盖你要删除的元素位置就好了,最后在修改数组的长度就好了,这里我使用容器vector存放数组,它可以智能调整数组长度,比自己调整方便~
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
int left = 0;
for (int right = 0; right < n; right++) {
if (nums[right] != val) {
nums[left] = nums[right];
left++;
}
}
return left;
}
};
总结
其实今天做了一道困难题,但是还有待提高的地方,就不发那个了~
边栏推荐
- Understand the reasons for impedance matching of PCB circuit board 2021-10-07
- VectorDraw Developer Framework 10.10
- Find out what informatization is, and let enterprises embark on the right path of transformation and upgrading
- RTKLIB-b33版本中GALILEO广播星历存储问题
- Accès à la boîte aux lettres du nom de domaine Lead à l'étranger
- 国外LEAD域名邮箱获取途径
- How comfortable it is to use Taijiquan to talk about distributed theory!
- OpenMP入门
- Introduction to Sichuan Tuwei ca-is3082wx isolated rs-485/rs-422 transceiver
- Pytorch遇到的坑:为什么模型训练时,L1loss损失无法下降?
猜你喜欢
Sichuan earth microelectronics 8-channel isolated digital input receiver
My debut is finished!
栅格地图(occupancy grid map)构建
MySQL facet 01
Summary of small problems in smartbugs installation
海思3559 sample解析:vio
CPDA|数据分析师成长之路如何起步?
[batch dos-cmd command - summary and summary] - CMD window setting and operation commands (CD, title, mode, color, pause, CHCP, exit)
ELK + filebeat日志解析、日志入库优化 、logstash过滤器配置属性
FairMOT yolov5s转onnx
随机推荐
57. 插入区间
ts环境搭建
PI Ziheng embedded: This paper introduces the multi-channel link mode of i.mxrt timer pit and its application in coremark Test Engineering
Misunderstanding of switching triode
Application scheme | application of Sichuan earth microelectronics ca-is398x in PLC field
VectorDraw Web Library 10.10
【批处理DOS-CMD命令-汇总和小结】-CMD窗口的设置与操作命令(cd、title、mode、color、pause、chcp、exit)
权限、认证系统相关名词概念
Pit encountered by pytorch: why can't l1loss decrease during model training?
机器学习笔记 - 时间序列的线性回归
AttributeError: ‘Upsample‘ object has no attribute ‘recompute_scale_factor‘
LeetCode 每日一题——515. 在每个树行中找最大值
OpenMP入门
点云智绘在智慧工地中的应用
[pytest] modify the logo and parameterization in the allure Report
Zhugeliang vs pangtong, taking distributed Paxos
Five causes of PCB board deformation and six solutions 2021-10-08
海思3559 sample解析:vio
MySQL face Scripture eight part essay
栅格地图(occupancy grid map)构建