java 简单二分MLE求助!!!!

P2249 【深基13.例1】查找

SCAU_Link @ 2024-03-03 23:06:41

用java写的,MLE

感觉数组也没开大

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] a = new int[n + 10];
        for (int i = 1; i <= n; ++i)
            a[i] = sc.nextInt();
        while (m-- != 0) {
            int q = sc.nextInt();
            int l = 0, r = n + 1;
            while (l + 1 < r) {
                int mid = l + r >> 1;
                if (a[mid] >= q)
                    r = mid;
                else
                    l = mid;
            }
            if (a[r] == q)
                System.out.print(r + " ");
            else
                System.out.print(-1 + " ");
        }
    }
}

by tengzhifei @ 2024-03-04 20:56:25

java得用快读


by SCAU_Link @ 2024-03-05 15:51:39

@tengzhifei 但是快读不是减少时间的吗,你可以去这道题的提交记录看看,语言选java,大量的人MLE,请教下怎么改


by tengzhifei @ 2024-03-14 23:05:05

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 re = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        re.nextToken();
        int n,m;
        n = (int)re.nval;
        re.nextToken();
        m= (int)re.nval;
        int []a=new int[n];
        for (int i=0;i<n;i++){
            re.nextToken();
            a[i]=(int)re.nval;
        }
        while(m-->0){
            re.nextToken();
            int cha=(int)re.nval;
            int l=0,r=n-1;
            while (l<r){
                int cet=(l+r)/2;
                if (cha>a[cet]){
                    l=cet+1;
                }
                else {
                    r=cet;
                }
            }
            if (a[r]==cha){
                System.out.print(r+1+" ");
            }
            else {
                System.out.print(-1+" ");
            }
        }
    }
}

|