【Java每日一题,左二分查找】Where is the Marble?

Introduction

现有 N 个大理石,每个大理石上写了一个非负整数。首先请你将这 N 块大理石按照它们上面所写数字的大小从小到大排序,然后按照排序后的顺序把这 N 个大理石从 1 ~ N 编号。之后请你回答 Q 个询问,每个询问问是否存在一个大理石上写着某个整数 x,如果存在,请你回答写着整数 x 的编号最小的大理石的编号,如果不存在,请你输出 x not found。

Input

有多组数据。
每组数据第一行包括两个整数 N,Q,当输入为 N = 0, Q = 0 时,表示结束。
否则接下来 Q 行,每一行包括一个数字 x,表示询问。

Output

对于每组测试数据,首先输出 “Case# XX”,XX 为测试数据编号,按读入顺序由 1 开始递增。
然后输出的话,下面的案例很清晰了。

Sample

input

4 1
2
3
5
1
5
5 2
1
3
3
3
1
2
3
0 0

output

CASE# 1:
5 found at 4
CASE# 2:
2 not found
3 found at 3

Solution


import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int index=1;
        while (true){
            int n=s.nextInt();int m=s.nextInt();
            if(n==0&&m==0)break;
            int[] arr=new int[n];
            for(int i=0;i<n;i++){
                arr[i]=s.nextInt();
            }
            Arrays.sort(arr);
            System.out.println("CASE# "+index+":");
            for(int j=0;j<m;j++){
                int k=s.nextInt();
                int i = binarySearch(arr, k);
                if(i==-1){
                    System.out.println(k+" not found");
                }else {
                    System.out.println(k+" found at "+i);

                }
            }
            index++;
        }
    }
    static int binarySearch(int[] arr,int k){
        int low=0,high=arr.length-1;
        while (low<high){
            int mid=(low+high)>>1;
            int key=arr[mid];
            if(k==key){
                high=mid;
            }else if(k<key) {
                high=mid-1;
            }else {
                low=mid+1;
            }
        }
        if(arr[low]!=k){
            return -1;
        }
        return low+1;
    }
}

Experience

第一次没有使用Arrays自带的二分查找的函数,因为要实现左二分的话,最好自己来实现。发现也没花多少时间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小梁说代码

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值