我是靠谱客的博主 沉默帆布鞋,这篇文章主要介绍LeeCode 27 移除元素,返回数组新长度,现在分享给大家,希望可以做个参考。

一、利标准库提供的移除算法remove()

复制代码
1
2
3
4
int removeElement(vector<int>& nums, int val) { remove(nums.begin(), nums.end(), val); return nums.size(); }

二、利用vector容器自带的删除函数erase()

复制代码
1
2
3
4
5
6
7
8
9
10
11
int removeElement(vector<int>& nums, int val) { auto it = nums.begin(); while (it != nums.end()) { if (*it == val) nums.erase(it); else it++; } return nums.size(); }

三、利用双指针,慢指针指向待删除元素,快指针后移找到其他元素,完成赋值,

复制代码
1
2
3
4
5
6
7
8
9
10
int removeElement(vector<int>& nums, int val) { int slowindex = 0; for (int fastindex = 0; fastindex != nums.size(); ++fastindex) { if (val != nums[fastindex]) nums[slowindex++] = nums[fastindex]; //本次赋值完成后,慢指针自增 //指向下一个元素,如果快指针遍历到了val,不做处理,继续后移,找到非val元素,赋值到慢指针所指位置 } return slowindex; }

 

最后

以上就是沉默帆布鞋最近收集整理的关于LeeCode 27 移除元素,返回数组新长度的全部内容,更多相关LeeCode内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部