快慢指针是指移动速度一快一慢的两个指针变量。通常有以下应用:
- 删除数组重复项;
- 判断链表是否存在环;
- 移除数组元素;
通过力扣的一道习题来练习下快慢指针的使用:
难度简单732收藏分享切换为英文接收动态反馈
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
示例 1:
给定 nums = [3,2,2,3], val = 3,
函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,1,2,2,3,0,4,2], val = 2,
函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
注意这五个元素可为任意顺序。
你不需要考虑数组中超出新长度后面的元素。
#include<iostream>
using namespace std;
int CutElem(int num[], int target, int n)
{
int flowindex = 0;
for(int fastindex = 0; fastindex < n; fastindex++)
{
if(num[fastindex] != target)
{
num[flowindex++] = num[fastindex];
}
}
return flowindex;
}
int main()
{
int a[5],b,m = 6;
int index;
cout << "The vector value is:" << endl;
for(int i = 0; i < m; i++)
{
cin >> a[i] ;
}
cout << "The target value is:" << endl;
cin >> b;
index = CutElem(a,b,m);
cout << "The new length is:"<<index <<endl;
}