Description
给出一个队列和要查找的数值,找出数值在队列中的位置,队列位置从1开始
要求使用带哨兵的顺序查找算法
Input
第一行输入n,表示队列有n个数据
第二行输入n个数据,都是正整数,用空格隔开
第三行输入t,表示有t个要查找的数值
第四行起,输入t个数值,输入t行
Output
每行输出一个要查找的数值在队列的位置,如果查找不成功,输出字符串error
Sample
Input
8
33 66 22 88 11 27 44 55
3
22
11
99
Output
3
5
error
Hint
测试用例组数不确定,用while(cin>>n){}一直循环测试
朴素顺序查找
思路很比较易理解,即构建一个队列后遍历,逐一和要查找的对象做比较,如果相等则令flag=1,输出这个值,若遍历完整个数据结构之后还没有找到,则flag=0,输出’error’。
#include <iostream>
#include<queue>
using namespace std;
int main() {
queue<int>q;
int n, num, i;
cin >> n;
for (i = 0; i < n; cin >> num, i++) {
q.push(num);
}
int t, aim;
cin >> t;
while (t--) {
cin >> aim;
int flag = 0;
queue<int>qq = q;
int now,j;
for (j = 0; !qq.empty(); j++) {
now = qq.front();
qq.pop();
if (now == aim) {
flag = 1;
cout << j << endl;
break;
}
}
if (!flag)
cout << "error" << endl;
}
return 0;
}
带哨兵的顺序查找
在search函数中,参数p是我们要查找的数组,aim是要查找的对象,我们将==哨兵值p[0]==设成我们要查找的对象aim,令p[0]=aim
,这样一来,我们在search函数while循环中就只需要一个判断条件–> p[loc] != aim
(当前位置的数组值不等于目标值),随之loc--
,而由于我们一开始设置了p[0] = aim,所以保证了在这个循环总数组不会越界,也就少了朴素顺序查找中!qq.empty()
的条件判断,利于提升代码性能且更利于理解。
此外,朴素顺序查找中的操作是对队列q的副本qq操作的,每查找一个数都需要对原队列复制一次,加了哨兵之后就不用这么麻烦。
#include<iostream>
using namespace std;
int search(int* p, int n, int aim) {
p[0] = aim;
int loc = n;
while (p[loc] != aim) {
loc--;
}
return loc;
}
int main() {
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int t, aim;
cin >> t;
while (t--) {
cin >> aim;
int loc = search(a, n, aim);
if (!loc)
cout << "error";
else cout << loc + 1; // 数组从零开始
cout << endl;
}
delete [] a;
return 0;
}