二分法
理解与总结
当题目给定一个区间,而且能够确定答案就在区间的内,这个时候就适合二分法求解答案,查找效率很高的一个算法,二分法有整数二分和实数二分,实数二分比较简单,印象中高中数学就学过了,下面主要讲整数二分,整数二分要区分答案是在答案区间的左端点还是右端点,如果是左端点就先缩小左边,反之先缩小右边,条件判断时先考虑相等情况,如果是寻找右端点需要在二分时加一再除以二(确保mid
总是偏向区间的右侧)。
例题
题目
789. 数的范围
思路
题目给定了一个区间[1,10000],让我们求询问数的起始位置和终点,可以又图看出,找起点可以看成时二分查找左端点,终点可以看成二分查找右端点。
代码
public class Main {
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
Scanner scan = new Scanner(System.in);
/*数组长度*/
int n = scan.nextInt();
int[] arr1 = new int[n];
/*询问个数*/
int q = scan.nextInt();
int[] arr2 = new int[q];
for (int i = 0; i < n; i++) {
arr1[i] = scan.nextInt();
}
for (int i = 0; i < q; i++) {
arr2[i] = scan.nextInt();
}
for (int i = 0; i < q; i++) {
int l = 0;
int r = n - 1;
int num = arr2[i];
/*寻找左端点*/
while (l < r) {
int m = l + r >> 1;
if (arr1[m] >= num) r = m;
else l = m + 1;
}
if (num == arr1[l]) {
out.write(l+" ");
/*寻找右端点*/
r = n - 1;
while (l < r) {
int m = l + r + 1 >> 1;
if (arr1[m] <= num) l = m;
else r = m -1;
}
if (num == arr1[l]) {
out.write(r + "\n");
}
} else out.write("-1 -1" + "\n");
}
out.flush();
}
}