当前位置:网站首页>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,但是右边的指针已经移动到前面去了。
边栏推荐
- Why can basic data types call methods in JS
- User management summary of mongodb
- 室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
- Centso7 OpenSSL error Verify return code: 20 (unable to get local issuer certificate)
- move base参数解析及经验总结
- [learning notes] agc010
- Unity build error: the name "editorutility" does not exist in the current context
- MongoDB优化的几点原则
- Read PG in data warehouse in one article_ stat
- php——laravel缓存cache
猜你喜欢
高端了8年,雅迪如今怎么样?
Cinnamon taskbar speed
作战图鉴:12大场景详述容器安全建设要求
Cloud detection 2020: self attention generation countermeasure network for cloud detection in high-resolution remote sensing images
Japanese government and enterprise employees got drunk and lost 460000 information USB flash drives. They publicly apologized and disclosed password rules
Esp32 ① compilation environment
Final review notes of single chip microcomputer principle
Custom thread pool rejection policy
xshell连接服务器把密钥登陆改为密码登陆
室內ROS機器人導航調試記錄(膨脹半徑的選取經驗)
随机推荐
User management summary of mongodb
室内ROS机器人导航调试记录(膨胀半径的选取经验)
Cinnamon taskbar speed
Ikvm of toolbox Net project new progress
最佳实践 | 用腾讯云AI意愿核身为电话合规保驾护航
迅为iTOP-IMX6ULL开发板Pinctrl和GPIO子系统实验-修改设备树文件
[Presto profile series] timeline use
Digital IC Design SPI
Fast development board pinctrl and GPIO subsystem experiment for itop-imx6ull - modify the device tree file
PHP - laravel cache
MongoDB优化的几点原则
JS function returns multiple values
Redis只能做缓存?太out了!
Introduction and basic use of stored procedures
Signal strength (RSSI) knowledge sorting
Why can basic data types call methods in JS
move base参数解析及经验总结
DID登陆-MetaMask
Centso7 OpenSSL error Verify return code: 20 (unable to get local issuer certificate)
Read PG in data warehouse in one article_ stat