🌗 704. 二分查找
2022年6月9日
- algorithm
🌗 704. 二分查找
难度: 🌗
问题描述
解法
class Solution {
public int search(int[] nums, int target) {
// 思路:
// 二分
int len = nums.length;
return mySol(nums, target, 0, len - 1);
}
private int mySol(int[] nums, int target, int left, int right) {
// 递归终止条件
if(left > right) {
return -1;
}
if(left == right) {
if(nums[left] == target) {
return left;
} else {
return -1;
}
}
// left < right
int mid = left + ((right - left) >> 1);
if(nums[mid] == target) {
return mid;
} else if(target > nums[mid]) {
left = mid + 1;
return mySol(nums, target, left, right);
} else {
right = mid - 1;
return mySol(nums, target, left, right);
}
}
}