1229: 二分查找(I)

题目描述
现在有一个长度为n的有序的序列,m次询问,每次会告诉你一个数字x,让你完成以下两种操作:
1.找到第一个大于等于x的值的下标,如果有多个等于的话找到第一个等于的下标
2.找到第一个大于x的值的下标
如果没有就输出NO,保证序列有序。

输入
第一行两个正整数n(n <= 100000)代表序列长度和m(m <= 100000)代表询问次数,第二行n个数字表示有序序列a(其中0 <= ai <= 200000)。接下来m行每行一个数字x(0 <= x <= 200000)。
输出
答案输出m行,每行两个数字分别表示答案,两个答案之间用空格隔开。
样例输入 Copy
5 5
1 3 4 5 6
1
2
3
6
7
样例输出 Copy
1 2
2 2
2 3
5 NO
NO NO

import java.io.*;
import java.nio.Buffer;
import java.util.*;
public class Main {
    static BufferedReader bf=new BufferedReader(new InputStreamReader((System.in)));
    static StreamTokenizer st=new StreamTokenizer(bf);
    static PrintWriter pw=new PrintWriter(System.out);
    static int I() throws IOException{
        st.nextToken();
        return (int) st.nval;
    }
    public static void main(String[] args) throws IOException {
        int n=I();
        int m=I();
        int[] arr=new int[n];
        for (int i = 0; i <n ; i++) {
            arr[i]=I();
        }
        while (m-->0){
            int p=I();
            int o=0;
            int l=0,r=n-1;
            while(l<r){
                int mid=(l+r)/2;
                if(arr[mid]>=p)r=mid;
                else{l=mid+1;}
            }

            if(l==n-1&&arr[l]<p){
                System.out.println("NO"+" NO");
                continue;
            }else if(p!=arr[l]){
                l++;
                System.out.println(l+" "+l);
                continue;
            }else if (p==arr[l]) {

                System.out.print((l+1)+" ");
                while (l<n-1){
                    l++;
                    if(arr[l]>arr[l-1]){
                        System.out.println(l+1);
                        o=-1;

                        break;
                    }
                }if(o!=-1) {
                    System.out.println("NO");
                }

            }
        }


    }
}

  • 11
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值