题目出处点这里
思路:二分树的高度,注意返回值即可
代码:
package binaryFindAndAnswer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class P1873 {
static int[] arr;
static int N;
static int M;
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
st.nextToken();
N = (int) st.nval;
arr = new int[N];// 初始化arr
st.nextToken();
M = (int) st.nval;
for (int i = 0; i < N; i++) {
st.nextToken();
arr[i] = (int) st.nval;
}
Arrays.sort(arr);// 升序
System.out.println(binary());
}
public static int binary() {
int l = 0, r = arr[N - 1];
while (l <= r) {
int mid = l + (r - l) / 2;
long sum = sum(mid);
if (sum > M) {
l = mid + 1;
}else if (sum < M) {
r = mid - 1;
}else {
return mid;
}
}
return l - 1;//l一定要减一,注意理解
}
public static long sum(int mid) {
long sum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > mid) {
sum = sum + arr[i] - mid;
}
}
return sum;
}
}