-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
43 lines (38 loc) · 980 Bytes
/
Copy pathBinarySearch.java
File metadata and controls
43 lines (38 loc) · 980 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package binarysearch;
/**
* 704. 二分查找 https://leetcode-cn.com/problems/binary-search/
*/
public class BinarySearch {
/**
* 左闭右合
*/
public int search1(int[] nums, int target) {
int lo = 0, hi = nums.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo >>> 1);
if (nums[mid] < target)
lo = mid + 1;
else if (nums[mid] > target)
hi = mid - 1;
else
return mid;
}
return -1;
}
/**
* 左闭右开
*/
public int search2(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo >>> 1);
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
lo = mid + 1;
else if (nums[mid] > target)
hi = mid;
}
return -1;
}
}