【Java】LeetCode题答-704二分查找
本帖最后由 孤樱懶契 于 2021-10-23 22:40 编辑# LeetCood题目
## !(https://gitee.com/gylq/cloudimages/raw/master/img/image-20210630045728618.png)
# 题答1(递归解法完整代码)
```java
//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 == target)
return mid;
if(data < target )
return search(data, mid + 1, r, target);
else
return search(data, l, mid - 1 , target);
}
}
```
# 题答2(非递归解法完整代码)
```java
//704
class Solution {
publicint search(int[] nums, int target){
int l = 0, r = nums.length - 1;
// 在data范围中查找 target
while(l <= r){
int mid = l + (r - l ) / 2;
if(nums[] == target)
return mid;
if(nums < target)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
}
```
# 测试截图
## 题答1
!(https://gitee.com/gylq/cloudimages/raw/master/img/image-20210630045847788.png)
## 题答2
!(https://gitee.com/gylq/cloudimages/raw/master/img/image-20210630051214790.png)
这个二分递归查找值得新手学习
页:
[1]