java语言的二分查找模板
- left < right - 1
- mid = left + (right - left) / 2 向下取整
- 找到相等的情况下, 向左向右看看
- 最后同时要判断下标是left 与 right 的数组值
class Solution {
public int findT(int[] nums, int target, boolean isRight) {
if(nums == null || nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
int mid = -1;
while(left < right - 1) {
mid = left + (right - left) / 2;
if(nums[mid] > target) {
right = mid - 1;
}else if(nums[mid] < target) {
left = mid + 1;
}else { // 重点,相等的情况下, 继续想右边看看有没有相等的
if(isRight) {
left = mid;
}else {
right = mid;
}
}
}
if( false == isRight) {
if(nums[left] == target) {
return left;
}else if(nums[right] == target) {
return right;
}
}else {
if(nums[right] == target) {
return right;
}else if(nums[left] == target) {
return left;
}
}
return -1;
}
}
网友评论