全re,最后一个WA,样例过了,求解

P2249 【深基13.例1】查找

yinY_ @ 2024-04-05 23:56:03


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer st1=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        st1.nextToken();
        int n=(int) st1.nval;
        st1.nextToken();
        int m = (int) st1.nval;
        int[]a= new int[n+10];
        int[]b= new int[m+10];
        for (int i = 1; i <=n; i++) {
            st1.nextToken();
            a[i]=(int) st1.nval;
        }
        for (int i = 1; i <= m; i++) {
            st1.nextToken();
            b[i]=(int) st1.nval;
        }
        for (int i = 1; i <=m; i++) {
            int l=0,r=a.length-1;
            int y=b[i];
            while(l<=r) {
                int mid=(l+r)/2;
                if (a[mid]>=y) {
                    r=mid-1;
                }else {
                    l=mid+1;
                }
            }
            if (a[l]==y) {
                System.out.print(l+" ");
            }else {
                System.out.println(-1+" ");
            }
        }
    }
}

|