题解 | #二分查找某数#
二分查找某数
https://www.nowcoder.com/practice/1aaf31d6e45b4ddb8cd10d12a660852a
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; //第一行输入一个n,k,其中n代表有n个数字,k代表你需要查找的元素 //第二行输入n个数 public class Main { static int index=-1; public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String[] line1=br.readLine().split(" ");//第一行 int n=Integer.parseInt(line1[0]);//n代表有n个数字 int k=Integer.parseInt(line1[1]);//k代表你需要查找的元素 String[] line2=br.readLine().split(" ");//第二行 int arr[]=new int[n]; for (int i = 0; i < line2.length; i++) { arr[i]=Integer.parseInt(line2[i]); } binary_search(arr,k); System.out.println(index); } public static void binary_search(int[] arr,int k) { int left=0; int right=arr.length-1; binary_search(left,right,arr,k); } public static void binary_search(int left,int right,int[] arr,int k) { if(left>right) { return; } int mid=(left+right)/2; if(arr[mid]==k) {//循环找最小下标 while((arr[mid]==k)&&mid>=0) { if(arr[mid]<=arr[mid+1]) { mid--; }else if(arr[mid]>arr[mid-1]) { index=mid; return; } } index=mid+1; }else if(arr[mid]>k) { right=mid-1; binary_search(left,right,arr,k); }else if(arr[mid]<k) { left=mid+1; binary_search(left, right,arr,k); } } }