使用双指针解决力扣27题《移除元素》
解决 元素 指针 27 力扣 移除 使用
2023-09-11 14:19:34 时间
题目描述不允许使用额外的数组空间,所以只能在原数组上操作。
我们使用两个指针,一个快指针 i 和一个慢指针 k 。i 每次移动一步,而 k 只在添加新的被需要的值时才移动一步。
因为我们的新数组的长度会小于等于旧数组,调用者在调用函数时根据返回的长度,它会打印出数组中该长度范围(k)内的所有元素。因此,范围外的元素不会输出。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int k = 0;
for(int i = 0; i < nums.size(); ++i)
{
if(nums[i] != val)
{
nums[k] = nums[i];
++ k;
}
}
return k;
}
};
相关文章
- [Web 前端] 解决因inline-block元素导致的空白间距和元素下沉
- spring mvc绑定对象String转Date解决入参不能是Date的问题
- php 8小时时间差的解决方法小结
- spss乱码问题解决
- IE6下position解决父元素被撑开的问题
- IE6下position解决父元素被撑开的问题
- helm部署hadoop报错解决方法
- Anaconda:成功解决Anaconda下载时速度超慢(conda下载慢)的几种方法图文教程
- 成功解决ValueError: DataFrame.dtypes for label must be int, float or bool
- 成功解决RuntimeWarning: divide by zero encountered in double_scalars
- 已解决MySQL 服务无法启动。
- python: not found 问题的解决
- 组合式应用新利器?SaaS新时代事件网格如何解决集成标准化问题
- 教你如何解决JS/TS里特定String进行拆分然后遍历各个元素
- 【云速建站】点击页面元素不跳转问题解决方法
- Leetcode 729. 我的日程安排表 I(牛逼,已解决)
- Leetcode 703. 数据流中的第 K 大元素(终于解决)
- VS2019多个项目调试时无法进入断点解决(亲测可用)
- 解决Error resolving template [x] template might not exist or might not be accessible by any of the con
- 成功解决:443端口被vmware-host(8992)占用。请关掉占用443端口的程序或者尝试使用系统代理模式
- 常见浏览器兼容性问题与解决方式
- 完美解决pkg_resources.DistributionNotFound: The ‘thop‘ distribution
- 如何解决Android Studiot版本4.2.2的Logcat无法输出日志的问题
- 【边缘设备】解决nanoPC-T4 upgrade报错
- No module named ‘tqdm‘的问题及解决