Problem Description
在一個給定的無重複元素的遞增序列裏,查找與給定關鍵字相同的元素,若存在則輸出找到的位置,不存在輸出-1。
Input
一組輸入數據,輸入數據第一行首先輸入兩個正整數n ( n < = 10^6 )和m ( m < = 10^4 ),n是數組中數據元素個數,隨後連續輸入n個正整數,輸入的數據保證數列遞增。
隨後m行輸入m個待查找的關鍵字key
Output
若在給定的序列中能夠找到與關鍵字key相等的元素,則輸出位序(序號從0開始),否則輸出-1。
Sample Input
8 3
4 6 8 9 13 20 21 22
6
8
17
Sample Output
1
2
-1
#include <stdio.h>
#include <string.h>
int a[1000005];
int sear(int left, int right, int x)
{
if(left>right) return -1;
else
{
int mid = (left + right) / 2;
if(a[mid]==x) return mid;
else if(x < a[mid]) return sear(left, mid-1, x);
else return sear(mid+1, right, x);
}
}
int main()
{
int n, m, i, re, x;
scanf("%d %d", &n, &m);
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
while(m--)
{
scanf("%d", &x);
re = sear(0, n-1, x);
printf("%d\n", re);
}
return 0;
}