1293A-ConneR and the A.R.C. Markland-N(ArrayList、二分查找)

ConneR and the A.R.C. Markland-N
题意:一栋楼有n层,某人在s层,这栋楼中每一层都有一间餐厅,其中有k层的餐厅是关闭的,求从第s层到最近的餐厅最少需要走多少层
题解:二分查找

import java.util.ArrayList;
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner scan=new Scanner(System.in);
        int t=scan.nextInt();
        while (t-->0){
            //楼层数
            int n=scan.nextInt();
            //所在的楼层
            int s=scan.nextInt();
            //关闭的餐馆数
            int k=scan.nextInt();
            int x;
            //泛型数据类型
            ArrayList<Integer> list=new ArrayList<>();
            for(int i=1;i<=k;i++){
                x=scan.nextInt();
                list.add(x);
            }
            int ans=0;
            //二分查找
            while (true){
                if(s+ans<=n&&!list.contains(s+ans)){
                    break;
                }
                if(s-ans>=1&&!list.contains(s-ans)){
                    break;
                }
                ans++;
            }
            System.out.println(ans);

        }
    }
}

重点:

  1. ArrayList<>(),添加关闭的餐厅
  2. 二分查找,从所在层数开始向两侧查找最近的餐厅

你可能感兴趣的:(ACM题解)