二分查找属于比较基础的算法之一
题目链接
题解
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid+1;
}
}
// while (left < right) {
// int mid = left + (right - left) / 2+1 ;
// if (nums[mid] <= target) {
// left = mid;
// } else {
// right = mid-1;
// }
// }
if (nums[left] == target){
return left;
}
// while (left <= right) {
// int mid = left + (right - left) / 2;
// if (nums[mid] < target) {
// left = mid+1;
// }else if (nums[mid]>target){
// right = mid-1;
// }else {
// return mid;
// }
// }
return -1;
}
}
二分查找思想分析
存在有序非递减且不重复数组nums,查询目标值target
设left = 0,right= nums.length-1;此时mid = (left+right)/2,如图则为2,判断nums[mid] 与目标值大小,如上图所示nums[mid]>=target时,此时搜索区间应该是[left,mid],即
为缩小区间,则令right = mid,再重复一次上述操作即可找到目标值
反过来同理,当nums[mid]<target时,此时搜索区间应该是[mid+1,right]
为缩小区间,则令left= mid+1,再重复一次上述操作即可找到目标值
建议
1.为防止整形溢出,使用
int mid = left + (right - left) / 2 代替int mid = (left + right) / 2
2.遇到条件为left = mid 时 使用
int mid = left + (right - left) / 2+1;
3.在非特殊情况下,while条件使用 left<right,这样退出while循环时,存在left = right
熟能生巧,这种题型多练练,理解其中思想,必要时用笔在纸上画画图