当前位置:网站首页>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;
}
};
总结
其实今天做了一道困难题,但是还有待提高的地方,就不发那个了~
边栏推荐
- 【批處理DOS-CMD命令-匯總和小結】-cmd擴展命令、擴展功能(cmd /e:on、cmd /e:off)
- Modular programming of wireless transmission module nRF905 controlled by single chip microcomputer
- npm install 报错 : gyp ERR! configure error
- Construction of occupancy grid map
- C#获取exe的版本号-文件版本and程序集版本
- 【QT】qtcreator便捷快捷键以及QML介绍
- AttributeError: ‘Upsample‘ object has no attribute ‘recompute_ scale_ factor‘
- Evolution of Alibaba e-commerce architecture
- (tool class) quickly add time to code in source insight
- 差点被这波Handler 面试连环炮带走~
猜你喜欢

el-input实现尾部加字

NPM install reports an error: gyp err! configure error

Three years of continuous decline in revenue, Tiandi No. 1 is trapped in vinegar drinks

Sichuan earth microelectronics ca-is1300 isolated operational amplifier for current detection is on the market

opencv最小值滤波(不局限于图像)

权限、认证系统相关名词概念

Chuantu microelectronics 𞓜 subminiature package isolated half duplex 485 transceiver

Zhugeliang vs pangtong, taking distributed Paxos

栅格地图(occupancy grid map)构建

OAuth 2.0一键登录那些事
随机推荐
指南针可以开股票账户吗?安全吗?
【批處理DOS-CMD命令-匯總和小結】-cmd擴展命令、擴展功能(cmd /e:on、cmd /e:off)
Shell tips (134) simple keyboard input recorder
國外LEAD域名郵箱獲取途徑
LeetCode 每日一题——515. 在每个树行中找最大值
VectorDraw Developer Framework 10.10
“空间转换”显著提升陡崖点云的地面点提取质量
Notes: [open class] neural network and deep learning -- tensorflow2.0 actual combat [Chinese course]
PI Ziheng embedded: This paper introduces the multi-channel link mode of i.mxrt timer pit and its application in coremark Test Engineering
Five causes of PCB board deformation and six solutions 2021-10-08
Vscode official configuration synchronization scheme
Evolution of Alibaba e-commerce architecture
China Mobile MCU product information
opencv最小值滤波(不局限于图像)
VectorDraw Web Library 10.10
Explain distributed raft with dynamic diagram
Cglib dynamic proxy
一次弄清楚 Handler 可能导致的内存泄漏和解决办法
一“石”二“鸟”,PCA有效改善机载LiDAR林下地面点部分缺失的困局
CPDA|数据分析师成长之路如何起步?