package week1;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int k=s.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=s.nextInt();
}
int key,low,high,mid;
while (k--!=0){
key=s.nextInt();
low=0;
high=n-1;
while (low<high){
mid=(low+high)>>1;
if(key<=arr[mid]){
high=mid;
}else
low = mid+1 ;
}
if(arr[low]==key)
System.out.print((low+1)+" ");
else
System.out.print(-1+" ");
}
s.close();
}
}
Experience 使用做二分查找,只需要key<=arr[mid]就行了
|