1.寻找符合条件的第一个数&最后一个数
package alg;
import bilibili.chapter16.Array;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Search {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(),q = sc.nextInt();
int []a = new int[100010];
for(int i=0;i<n;i++) a[i]=sc.nextInt();
System.out.println(Arrays.toString(a));
while(q-->0){
int k = sc.nextInt();
int l = 0,r = n-1;
while (l<r){
int mid = l+r>>1;
if(a[mid]>=k) r = mid;
else l = mid + 1;
}
System.out.println(l);
int left = l;
if(a[l]!=k) System.out.println("-1 -1");
else {
l = 0;
r = n - 1;
while (l<r){
int mid = l+r+1>>1;
if(a[mid]<=k) l = mid;
else r = mid - 1;
}
System.out.println(left+" "+r);
}
}
}
}
2.浮点数二分
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x = sc.nextDouble();
double l = -10000,r = 10000;
while(r - l >1e-8){
double mid = (l+r)/2;
if(mid*mid*mid>=x) r = mid;
else l = mid;
}
System.out.printf("%.6f",r);
}
}