热身题:704. 二分查找
题目描述:
链接:https://leetcode.cn/problems/binary-search/description/
关键点:区间的开闭选择
原则就是:要开都开,要闭都闭,前后保持一致即可。
解法一:左闭右闭
代码与注释:
class Solution {
public int search(int[] nums, int target) {
//使用左闭右闭
// 初始左边界
int left = 0;
// 初始右边界
int right = nums.length - 1;
while(left <= right){
//求中间索引,注意是(左边界+右边界)/2
int midIndex = (left + right) / 2;
//进行比较
if(target == nums[midIndex]){
return midIndex;
}
else if(target < nums[midIndex]){
//已经确定小于num[midIndex]了,所以下一次的边界就不需要包含他了
//所以是right = midIndex-1;
right = midIndex-1;
}
else{
left = midIndex + 1;
}
}
//搜索完了,没有找到
return -1;
}
}
运行结果:
解法二:左闭右开
代码和注释:
class Solution {
public int search(int[] nums, int target) {
//使用左闭右开
//初始左边界
int left = 0;
//初始右边界
int right = nums.length;
while(left < right){
int midIndex = (left + right)/2;
if(target == nums[midIndex]){
return midIndex;
}
else if(target < nums[midIndex]){
//target < nums[midIndex],下一次的区间应该不包含nums[midIndex]
//因为是左闭右开,所以就是:right = midIndex;
right = midIndex;
}
else{
left = midIndex + 1;
}
}
return -1;
}
}