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