题解 | 找x 动态数组,注意找到后的处理,否则会多输出-1
找x
https://www.nowcoder.com/practice/069e2130430c41229ab25e47fa0949a6
#include <iostream>
#include <vector> // 数据长度未知,用动态数组
using namespace std;
int main() {
int n, target;
// 迭代器需要另配 记录下标的数据
while (cin >> n) {
vector<int> dataSource(n);
for (int i = 0; i < n; i++) {
cin >> dataSource[i];
}
cin >> target;
for (int i = 0; i < n; i++) {
if (target == dataSource[i]) {
cout << i << endl;
break; // 找到了,退出循环
} else if (i == n -
1) { // 到数组尾部 不能为n,否则不能进入循环
cout << "-1" << endl;
}
}
}
return 0;
}
#考研##复试练习##笔试#2025考研复试 文章被收录于专栏
复试ing,努力中。。。


查看6道真题和解析