题解 | #序列中删除指定数字#
序列中删除指定数字
https://www.nowcoder.com/practice/7bbcdd2177a445a9b66da79512b32dd7
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
int a[N];
for (int i = 0; i < N; ++i)
{
cin >> a[i];
}
int del;
cin >> del;
int i = 0;
int k = N - 1;
while (a[k] == del)
{
k--;
}
while (i != k)
{
if (a[i] == del)
{
do {
int t = i;//保存i
for (int j = i + 1; j <= k; ++j, ++i)
{
a[i] = a[j];
}
i = t;
--k;
}while (a[i] == del);
}
if (i != k)
++i;
}
for (int t = 0; t <= k ; ++t)
{
cout << a[t] << " ";
}
}
// 64 位输出请用 printf("%lld")
思路是当发现要发现要删除的元素,后面的元素往前移动,最后输出的是前面不是删除元素的序列,所以要注意最后终点k的初值要从后往前遍历直到找到第一个不是删除元素的元素。
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路
