刚刚腾讯模拟题编程题,二分查找有问题
第一种解法:
package com;
import java.util.*;
/**
* 满足三个节点值不在同一边可以了,root>min root<max
* @author Admin
*
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int max = Math.max(a, Math.max(b,c));
int min = Math.min(a, Math.min(b,c));
int root = getMinRoot(k);
//如果最小根节点root>max表示max在root左边
while(max<root){
k--;
root -= getMinRoot(k);
}
while(min>root){
k--;
root += getMinRoot(k);
}
System.out.println(root);
}
private static int getMinRoot(int k){
//取中间节点作为比较的根节点
int root = (int)(Math.pow(2,k)/2);
return root;
}
}
第二种解法:二分查找
package com;
import java.util.*;
public class Main01 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int k = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
int max = Math.max(a, Math.max(b,c));
int min = Math.max(a, Math.min(b,c));
int high = (int)(Math.pow(2,k)-1);
int low = 1;
while(low<high){
int middle = (low+high)/2;
if(middle>=min&&middle<=max){
System.out.println(middle);
break;
}else if(middle>max){
high=middle-1;
}else{
low=middle+1;
}
}
}
}
但是第二种解法,测试用例有问题:

