力扣 LeetCode 704. 二分查找
解题思路:
二分查找主要分为[ left , right ]左闭右闭和[ left , right )左闭右开两种
此处采取[ left , right ]左闭右闭写法
注意:
1. right的初始化取值
2. while中取等
3. right = mid -1 ;
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) >> 1);
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
return mid;
}
}
return -1;
}
}
原文地址:https://blog.csdn.net/qq_61504864/article/details/143680435
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!