789. 数的范围
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int q = sc.nextInt();int[] res = new int[n];for(int i=0;i<n;i++)res[i] = sc.nextInt();while(q-- != 0) {int m = sc.nextInt();//先找左端点再找右端点int l = 0,r = n-1;while(l<r) {int mid = (l+r)/2;if(res[mid]>=m) r = mid;else l = mid + 1;}//l和r相等if(res[l] == m) {System.out.print(l+" ");//缩小搜索范围到(左端点到n-1)r = n-1;while(l<r) {int mid = (l+r+1)/2;//+1if(res[mid]<=m) l = mid;else r = mid-1;}System.out.println(r);}else {System.out.println("-1 -1");}}}
}
790. 数的三次方根
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);double n = sc.nextDouble();double l = -10000,r = 10000;while((r-l)>1e-8) {//保留6位多写两位double mid = (l+r)/2;if((mid*mid*mid) >= n) r = mid;//!!else l = mid;}System.out.printf("%.6f",l);}
}
P2249 【深基13.例1】查找
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;public class Main {public static void main(String[] args) throws IOException{BufferedReader br = new BufferedReader(new InputStreamReader(System.in));PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); String[] s1 = br.readLine().split(" ");int n = Integer.parseInt(s1[0]);int m = Integer.parseInt(s1[1]);int[] res = new int[n+1];String[] s2 = br.readLine().split(" ");for(int i=1;i<=n;i++)res[i] = Integer.parseInt(s2[i-1]);String[] s3 = br.readLine().split(" ");int k = 0;while(m-- != 0) {int z = Integer.parseInt(s3[k++]);int l = 1,r = n;while(l<r) {int mid = (l+r)/2;if(res[mid] >= z) r = mid;else l = mid + 1;}if(res[l] == z) {System.out.print(l+" ");}else {System.out.print("-1 ");}}}
}