题目来源
Leetcode 704题 二分查找,链接如下
Problem: 704. 二分查找
思路
- 循环之前先做一个简单的判断
- 循环条件为nums[left] <= nums[right]
如果target == nums[middle],最好情况,直接返回middle即可
如果target > nums[middle],说明target 值在middle和right之间,且不为middle,所以left = middle + 1;
如果如果target < nums[middle],说明target 值在left和middle之间,且不为middle,所以 right = middle - 1;
Code
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int middle = 0;
//循环之前先简单判断一下
if (target < nums[left] || target > nums[right]) {
return -1;
}
while(nums[left] <= nums[right]){
middle = (left + right) / 2;
if(target == nums[middle]) {
return middle;
} else if(target > nums[middle]) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}
}