java 80分求助,最后一个点TLE

P2249 【深基13.例1】查找

XieLee @ 2023-02-08 10:29:51

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;

public class Main {
    static StreamTokenizer st= new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    public static void main(String[] args) {
        PrintWriter pw =new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n=nextInt();
        int m=nextInt();
        int []arr=new int[n];
        int []can=new int[m];
        for(int i=0;i<n;i++)
        {
            arr[i]=nextInt();
        }
        for(int i=0;i<m;i++)
        {
            can[i]=nextInt();
        }
        StringBuilder sb=new StringBuilder();
        for(int j=0;j<m;j++)
        {
            sb.append(erfen(can[j],arr,0,arr.length-1)+1+" ");
        }
        pw.print(sb);
        pw.flush();
    }
    private static int erfen(int i, int[] arr,int start,int end) {
        if(start==end&&arr[start]!=i)
        {
            return -2;
        }
        int loc =(start+end)>>1;
        if(i==arr[loc])
        {
            while(loc-1>=0&&arr[loc-1]==i)
            {
                loc--;
            }
            return loc; 
        }else if(i<arr[loc])
        {
            return erfen(i,arr,start,loc);
        }
        else
        {
            return erfen(i,arr,loc+1,end);
        }

    }
    static int nextInt() {
        try {
            st.nextToken();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        return (int)st.nval;
    }
}

前面是啊金都正常,就最后一个点,超时,怀疑超长数据,都是一个值


by XieLee @ 2023-02-08 10:33:28

我增加判断,起点如果等于当前值直接返回,避免了这种情况,最后一点还是超时,不知道因为什么了


by lsiuf @ 2023-02-17 17:36:23

试下不用StringBuilder?直接在循环里面pw.print(erfen());

我也是java,手写二分AC了,用StringBuilder拼字符串然后indexOf,全部TLE


|