当前位置:网站首页>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,但是右边的指针已经移动到前面去了。
边栏推荐
- Write it down once Net a new energy system thread surge analysis
- MongoDB 分片总结
- Error lnk2019: unresolved external symbol
- Cloud detection 2020: self attention generation countermeasure network for cloud detection in high-resolution remote sensing images
- MongoDB 遇见 spark(进行整合)
- 我那“不好惹”的00后下属:不差钱,怼领导,抵制加班
- Solve the cache breakdown problem
- Pcap learning notes II: pcap4j source code Notes
- MongoDB命令汇总
- 一文读懂数仓中的pg_stat
猜你喜欢

室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)

JS缓动动画原理教学(超细节)

Cinnamon 任务栏网速

LIS 最长上升子序列问题(动态规划、贪心+二分)

Cmake learning and use notes (1)

PAcP learning note 1: programming with pcap

Introduce six open source protocols in detail (instructions for programmers)

Custom thread pool rejection policy

最佳实践 | 用腾讯云AI意愿核身为电话合规保驾护航

OSI seven layer model
随机推荐
User management summary of mongodb
干货|总结那些漏洞工具的联动使用
Problems that cannot be accessed in MySQL LAN
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
学习突围2 - 关于高效学习的方法
Redis只能做缓存?太out了!
将数学公式在el-table里面展示出来
Realbasicvsr test pictures and videos
10 pictures open the door of CPU cache consistency
Cinnamon 任务栏网速
JS determines whether an object is empty
Read PG in data warehouse in one article_ stat
[dark horse morning post] Huawei refutes rumors about "military master" Chen Chunhua; Hengchi 5 has a pre-sale price of 179000 yuan; Jay Chou's new album MV has played more than 100 million in 3 hours
Read PG in data warehouse in one article_ stat
最佳实践 | 用腾讯云AI意愿核身为电话合规保驾护航
一文读懂数仓中的pg_stat
xshell连接服务器把密钥登陆改为密码登陆
线程池拒绝策略最佳实践
一文读懂数仓中的pg_stat
High end for 8 years, how is Yadi now?