Java-二分最终版本

还得是闭区间

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.MissingFormatArgumentException;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger;

import javax.sound.midi.MidiChannel;
import javax.swing.event.AncestorEvent;

class in 
{
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer tokenizer = new StringTokenizer("");
    
    static String nextLine() throws IOException   { return reader.readLine(); }
    
    static String next() throws IOException 
    {
        while (!tokenizer.hasMoreTokens())  tokenizer = new StringTokenizer(reader.readLine());
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException  { return Integer.parseInt(next()); }

    static double nextDouble() throws IOException { return Double.parseDouble(next()); }
    
    static long nextLong() throws IOException  { return Long.parseLong(next());}
    
    static BigInteger nextBigInteger() throws IOException 
    { 
        BigInteger d = new BigInteger(in.nextLine());
        return d;
    }
}

public class Main 
{
    static final int N = (int) (1e5 + 10);
    static int a[] = new int [N];
    public static void main(String[] args) throws IOException 
    {
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        
        int n = in.nextInt();
        int k = in.nextInt();
        for(int i = 0 ; i < n ; i ++)  a[i] = in.nextInt();
        
        while(k -- > 0)
        {
            int x = in.nextInt();
            
            // 寻找左端点
            int l = 0,r = n - 1;
            while(l <= r)
            {
                int mid = l + r >> 1;
                if(a[mid] < x)  l = mid + 1;
                else if(a[mid] == x)  r = mid - 1;
                else if(a[mid] > x)  r = mid - 1;
            }
            
            if(a[l] == x)
            {
                out.print(l + " ");
                
                // 寻找右端点
                l = 0;
                r = n - 1;
                while(l <= r)
                {
                    int mid = l + r >> 1;
                    if(a[mid] < x)  l = mid + 1;
                    else if(a[mid] == x)  l = mid + 1;
                    else if(a[mid] > x)  r = mid - 1;  
                }
                
                out.println(r + " ");
            }
            else out.println("-1 -1");
        }       
        out.flush();
    }
}

你可能感兴趣的:(java,java)