數的範圍(整數二分)

給定一個按照升序排列的長度爲n的整數數組,以及 q 個查詢。java

對於每一個查詢,返回一個元素k的起始位置和終止位置(位置從0開始計數)。數組

若是數組中不存在該元素,則返回「-1 -1」。spa

輸入格式

第一行包含整數n和q,表示數組長度和詢問個數。code

第二行包含n個整數(均在1~10000範圍內),表示完整數組。xml

接下來q行,每行包含一個整數k,表示一個詢問元素。blog

輸出格式

共q行,每行包含兩個整數,表示所求元素的起始位置和終止位置。io

若是數組中不存在該元素,則返回「-1 -1」。class

數據範圍

1n1000001≤n≤100000
1q100001≤q≤10000
1k100001≤k≤10000
import

輸入樣例:

6 3
1 2 2 3 3 4
3
4
5

輸出樣例:

3 4
5 5
-1 -1

能夠直接順序查找,但時間O(n);而二分查找時間O(logn)
import java.util.Scanner;

public class Main {
         public static void main(String[] args) {
               Scanner scan=new Scanner(System.in);
               int n=scan.nextInt();
               int q=scan.nextInt();
               int a[]=new int[n];
               for(int i=0;i<n;i++) a[i]=scan.nextInt();
               while(q-->0){
                    int num=scan.nextInt();
                    //先找到左邊界
                    int l=0,r=n-1;
                    while(l<r){
                         int mid=l+r>>1;
                         if(a[mid]>=num) r=mid;
                         else l=mid+1;
                    }
                    if(a[l]!=num){
                          System.out.println("-1 -1");
                    }
                    //若是有這個數,再找右邊界
                    else{
                          System.out.print(l+" ");
                          l=0;r=n-1;
                          while(l<r){
                                 int mid=l+r+1>>1;
                                 if(a[mid]<=num) l=mid;
                                 else r=mid-1;
                          }
                          System.out.println(l);
                    }
               }
        }
}
相關文章
相關標籤/搜索