当前位置:网站首页>LeetCode 27. 移除元素
LeetCode 27. 移除元素
2022-07-02 06:07:00 【大白羊_Aries】
题目描述
解法
解法还是快慢指针:如果 fast 遇到值为 val 的元素,则直接跳过,否则就赋值给 slow 指针,并让 slow 前进一步
但是,注意这里和有序数组去重(26. 删除有序数组中的重复项)的解法有一个细节差异,我们这里是先给 nums[slow] 赋值然后再给 slow++,这样可以保证 nums[0…slow-1] 是不包含值为 val 的元素的,最后的结果数组长度就是 slow
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if (nums.size() == 0) return 0;
int slow = 0, fast = 0;
while (fast < nums.size())
{
if (nums[fast] != val)
{
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}
};
边栏推荐
- Shenji Bailian 3.52-prim
- 格式校验js
- PHP gets CPU usage, hard disk usage, and memory usage
- Shenji Bailian 3.53-kruskal
- 步骤详解 | 助您轻松提交 Google Play 数据安全表单
- Introduce uview into uni app
- Contest3147 - game 38 of 2021 Freshmen's personal training match_ G: Flower bed
- On Web server
- Happy Lantern Festival | Qiming cloud invites you to guess lantern riddles
- Contest3147 - game 38 of 2021 Freshmen's personal training match_ 1: Maximum palindromes
猜你喜欢
Little bear sect manual query and ADC in-depth study
How to use mitmproxy
Test case
【C语言】简单实现扫雷游戏
从设计交付到开发,轻松畅快高效率!
Leverage Google cloud infrastructure and landing area to build enterprise level cloud native excellent operation capability
在uni-app中引入uView
CNN可视化技术 -- CAM & Grad-CAM详解及pytorch简洁实现
Google Go to sea entrepreneurship accelerator registration countdown 3 days, entrepreneurs pass through the guide in advance collection!
Summary of MySQL constraints
随机推荐
Ros2 --- lifecycle node summary
Google Go to sea entrepreneurship accelerator registration countdown 3 days, entrepreneurs pass through the guide in advance collection!
Redis Key-Value数据库【初级】
Leverage Google cloud infrastructure and landing area to build enterprise level cloud native excellent operation capability
ZABBIX server trap command injection vulnerability (cve-2017-2824)
PHP parent
Brain and cognitive neuroscience matlab psychoolbox cognitive science experimental design - experimental design 4
Zabbix Server trapper 命令注入漏洞 (CVE-2017-2824)
Lambda expressions and method references
Web页面用户分步操作引导插件driver.js
Detailed notes of ES6
Shenji Bailian 3.54-dichotomy of dyeing judgment
Error creating bean with name 'instanceoperatorclientimpl' defined in URL when Nacos starts
Format check JS
The official zero foundation introduction jetpack compose Chinese course is coming!
Problems encountered in uni app development (continuous update)
STC8H8K系列汇编和C51实战——串口发送菜单界面选择不同功能
数据回放伴侣Rviz+plotjuggler
Comment utiliser mitmproxy
Eco express micro engine system has supported one click deployment to cloud hosting