当前位置:网站首页>2022-7-6 Leetcode27. Remove the element - I haven't done the problem for a long time. It's such an embarrassing day for double pointers
2022-7-6 Leetcode27. Remove the element - I haven't done the problem for a long time. It's such an embarrassing day for double pointers
2022-07-07 13:38:00 【weixin_ fifty-one million one hundred and eighty-seven thousand】


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;
}
};
Two points to pay attention to :
1)while (leftIdx < nums.size() && nums[leftIdx++] != val);
You can't write it like that , Because if the current !=val, It will also move forward one
2) And can't write leftIdx < nums.size().
Because it's possible rightIdx The following numbers are val, But the pointer on the right has moved to the front .
边栏推荐
- JS function returns multiple values
- Oracle advanced (V) schema solution
- LIS longest ascending subsequence problem (dynamic programming, greed + dichotomy)
- 提升树莓派性能的方法
- QQ的药,腾讯的票
- [etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
- Clion mingw64 Chinese garbled code
- Getting started with MySQL
- 【堡垒机】云堡垒机和普通堡垒机的区别是什么?
- Detr introduction
猜你喜欢
随机推荐
Navicat运行sql文件导入数据不全或导入失败
How to make join run faster?
Leecode3. Longest substring without repeated characters
[learning notes] segment tree selection
Custom thread pool rejection policy
Scripy tutorial classic practice [New Concept English]
toRaw和markRaw
What parameters need to be reconfigured to replace the new radar of ROS robot
MongoDB 遇见 spark(进行整合)
Fast development board pinctrl and GPIO subsystem experiment for itop-imx6ull - modify the device tree file
Indoor ROS robot navigation commissioning record (experience in selecting expansion radius)
Enregistrement de la navigation et de la mise en service du robot ROS intérieur (expérience de sélection du rayon de dilatation)
数据库系统概论-第一章绪论【概念模型、层次模型和三级模式(外模式、模式、内模式)】
Introduction and basic use of stored procedures
Data refresh of recyclerview
118. 杨辉三角
Build a secure and trusted computing platform based on Kunpeng's native security
postgresql array类型,每一项拼接
[Presto profile series] timeline use
Distributed transaction solution









