顺序表应用6:有序顺序表查询
Time Limit: 1000 ms Memory Limit: 4096 KiB
Problem Description
顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
Input
第一行输入整数n (1 <= n <= 100000),表示顺序表的元素个数;
第二行依次输入n个各不相同的有序非负整数,代表表里的元素;
第三行输入整数t (1 <= t <= 100000),代表要查询的次数;
第四行依次输入t个非负整数,代表每次要查询的数值。
保证所有输入的数都在 int 范围内。
Output
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Sample Input
10
1 22 33 55 63 70 74 79 80 87
4
55 10 2 87
Sample Output
4
No Found!
No Found!
10
正常查找的话会超时, 数据量大,用二分查找,以下为代码:
#include <stdio.h>
#include <stdlib.h>
int List[100010];
int i, j, k;
int search(int a[], int lt, int rt, int x)
{
while(lt <= rt)
{
int mid = (rt + lt) / 2;
if(a[mid] == x)
return mid+1;
else if(a[mid] < x)
{
lt = mid + 1;
}
else if(a[mid] > x)
{
rt = mid-1;
}
}
return 0;
}
int main()
{
int n, t, x;
scanf("%d", &n);
for(i=0; i<n; i++)
{
scanf("%d", &List[i]);
}
scanf("%d", &t);
while(t--)
{
scanf("%d", &x);
k = search( List, 0, n-1, x);
if(k)
printf("%d\n", k);
else
printf("No Found!\n");
}
return 0;
}
/***************************************************
Result: Accepted
Take time: 60ms
Take Memory: 488KB
Submit time: 2018-03-10 21:03:20
****************************************************/
01 |
#include <stdio.h> |
02 |
#include <stdlib.h> |
03 |
|
04 |
int List[100010]; |
05 |
int i, j, k; |
06 |
|
07 |
int search( int a[], int lt, int rt, int x) |
08 |
{ |
09 |
while (lt <= rt) |
10 |
{ |
11 |
int mid = (rt + lt) / 2; |
12 |
if (a[mid] == x) |
13 |
return mid+1; |
14 |
else if (a[mid] < x) |
15 |
{ |
16 |
lt = mid + 1; |
17 |
} |
18 |
else if (a[mid] > x) |
19 |
{ |
20 |
rt = mid-1; |
21 |
} |
22 |
} |
23 |
return 0; |
24 |
} |
25 |
|
26 |
int main() |
27 |
{ |
28 |
int n, t, x; |
29 |
scanf ( "%d" , &n); |
30 |
for (i=0; i<n; i++) |
31 |
{ |
32 |
scanf ( "%d" , &List[i]); |
33 |
} |
34 |
scanf ( "%d" , &t); |
35 |
while (t--) |
36 |
{ |
37 |
scanf ( "%d" , &x); |
38 |
k = search( List, 0, n-1, x); |
39 |
if (k) |
40 |
printf ( "%d\n" , k); |
41 |
else |
42 |
printf ( "No Found!\n" ); |
43 |
} |
44 |
return 0; |
45 |
} |