目录
二分查找法的基本思想
查找过程
一个排好序的数组(本文假设升序),查找有没有某个数target,如果有,返回其下标,如果没有,返回-1
二分查找法就是折半地去寻找,通过比对这一半的最中间的值,是否与target相等,如果不等,在折一半
例如 nums=[-1,3,5,6,7,9], 目标target=7
val | -1 | 3 | 5 | 6 | 7 | 9 |
step1 | min=0 | mid=2 | max=5 | |||
step2 | min=3 | mid=4 | max=5 | |||
step3 | mid=target |
时间复杂度
O(log2n)
因为,折半找,也就是第一次查找的范围是这个数组元素个数n的1/2,即,第二次是n的1/4,即,第三次1/8……
直到最后一次(第t次),也就是查找的范围剩下一个值了,也就是,,由此可以得到,所以时间复杂度就是O(log2n)
优缺点
优点:效率较高,比较次数小
缺点:待查找的数组,必须是有序的。
代码实现
public int search(int[] nums, int target) {
int min = 0;
int max = nums.length-1;
//while 条件中,需要等号,因为 如果只有一个元素,会出错
while(max>=min){
int mid = min + (max-min)/2;
if(target == nums[mid]){
return mid;
}else if(target>nums[mid]){
//min = mid; 是错的,因为这样会导致死循环
min = mid+1;
max = max;
}else if (target<nums[mid]){
//max = mid;同理,也不能这样定义
max = mid-1;
min = min;
}
}
return -1;
}