当前位置:网站首页>2022-7-6 Leetcode27.移除元素——太久没有做题了,为双指针如此狼狈的一天
2022-7-6 Leetcode27.移除元素——太久没有做题了,为双指针如此狼狈的一天
2022-07-07 11:36:00 【weixin_51187533】


class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int leftIdx = 0;
int rightIdx = nums.size()-1;
while (leftIdx <= rightIdx){
while (leftIdx <= rightIdx && nums[leftIdx] != val){
leftIdx++;
}
while (leftIdx <= rightIdx&& nums[rightIdx] == val){
rightIdx--;
}
if (leftIdx < rightIdx)
nums[leftIdx++] = nums[rightIdx--];
}
return leftIdx;
}
};
两个需要注意的点:
1)while (leftIdx < nums.size() && nums[leftIdx++] != val);
不能这样写,因为如果当前的!=val,也会向前移动一个
2)以及不能写leftIdx < nums.size()。
因为很可能rightIdx后面的数字还有val,但是右边的指针已经移动到前面去了。
边栏推荐
- PAcP learning note 3: pcap method description
- Cinnamon 任务栏网速
- 《厌女:日本的女性嫌恶》摘录
- shell 批量文件名(不含扩展名)小写改大写
- Talk about pseudo sharing
- JS slow motion animation principle teaching (super detail)
- MongoDB的导入导出、备份恢复总结
- [1] Basic knowledge of ros2 - summary version of operation commands
- 将数学公式在el-table里面展示出来
- [learning notes] segment tree selection
猜你喜欢

Cinnamon taskbar speed

Error lnk2019: unresolved external symbol

Storage principle inside mongodb

交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)

Ogre introduction

How to make join run faster?

迅为iTOP-IMX6ULL开发板Pinctrl和GPIO子系统实验-修改设备树文件

【堡垒机】云堡垒机和普通堡垒机的区别是什么?

Cloud detection 2020: self attention generation countermeasure network for cloud detection in high-resolution remote sensing images

《厌女:日本的女性嫌恶》摘录
随机推荐
Scrapy教程经典实战【新概念英语】
Milkdown 控件图标
Error lnk2019: unresolved external symbol
提升树莓派性能的方法
PAcP learning note 3: pcap method description
室内ROS机器人导航调试记录(膨胀半径的选取经验)
JS function returns multiple values
Simple and easy-to-use code specification
聊聊伪共享
RealBasicVSR测试图片、视频
Navicat运行sql文件导入数据不全或导入失败
[etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
[learning notes] segment tree selection
Scripy tutorial classic practice [New Concept English]
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
flask session伪造之hctf admin
干货|总结那些漏洞工具的联动使用
Ogre入门尝鲜
How did Guotai Junan Securities open an account? Is it safe to open an account?
MongoDB 分片总结