class Solution {
private:
int binarySearch(vector<int>& nums,int l, int r, int target){
if(l >= r) return -1;
int mid = (l + r) >> 1;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) return binarySearch(nums, l, mid, target); // [l, mid)
else return binarySearch(nums, mid + 1, r, target); // [mid + 1, r)
}
public:
int search(vector<int>& nums, int target) {
return binarySearch(nums, 0, nums.size(), target); //查找范围: [0, nums.size()) 左闭右开
}
};
<Talk is cheap, show me the code 25> LeetCode.704 二分查找
最新推荐文章于 2024-09-10 23:34:31 发布