题解 | #二分查找-I#
二分查找-I
https://www.nowcoder.com/practice/d3df40bd23594118b57554129cadf47b
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
public int search (int[] nums, int target) {
// write code here
int a = 0;//分支的头
int b = nums.length-1;//分支的尾
while(a <= b){//分支的头>尾意味着所有元素都已排查完成
int c = (a + b)/2;//二分的中间值下标
if(nums[c] == target){
return c;
}else if(nums[c]> target){//进入到左半部
b = c - 1;
}else{//进入到右半部
a = c + 1;
}
}
return -1;
}
}

查看5道真题和解析