本帖最后由 孤樱懶契 于 2021-10-23 22:40 编辑
LeetCood题目
题答1(递归解法完整代码)
//704
class Solution {
public int search(int[] nums, int target) {
return search(nums ,0, nums.length-1, target);
}
private int search(int[] data, int l , int r, int target){
if(l > r) return -1;
int mid = l + (r - l) / 2;
if(data[mid] == target)
return mid;
if(data[mid] < target )
return search(data, mid + 1, r, target);
else
return search(data, l, mid - 1 , target);
}
}
题答2(非递归解法完整代码)
//704
class Solution {
public int search(int[] nums, int target){
int l = 0, r = nums.length - 1;
// 在data[l, r ]范围中查找 target
while(l <= r){
int mid = l + (r - l ) / 2;
if(nums[][mid] == target)
return mid;
if(nums[mid] < target)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
}
测试截图
题答1
题答2
|