-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathBinarySearch.java
87 lines (72 loc) · 2.66 KB
/
BinarySearch.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Created by liuyubobobo on 11/21/17.
*/
public class BinarySearch {
private BinarySearch(){}
// 二分查找法, 在一个有序数组arr中, 寻找大于等于target的元素的第一个索引
// 如果存在, 则返回相应的索引index
// 否则, 返回arr的元素个数 n
// 相当于 lower_bound
public static int firstGreaterOrEqual(Comparable[] arr, Comparable target){
if(arr == null)
throw new IllegalArgumentException("arr can not be null.");
int l = 0, r = arr.length;
while(l != r){
int mid = l + (r - l) / 2;
if(arr[mid].compareTo(target) < 0)
l = mid + 1;
else // nums[mid] >= target
r = mid;
}
return l;
}
// 二分查找法, 在一个有序数组arr中, 寻找大于target的元素的第一个索引
// 如果存在, 则返回相应的索引index
// 否则, 返回arr的元素个数 n
// 相当于 upper_bound
public static int firstGreaterThan(Comparable[] arr, Comparable target){
if(arr == null)
throw new IllegalArgumentException("arr can not be null.");
int l = 0, r = arr.length;
while(l != r){
int mid = l + (r - l) / 2;
if(arr[mid].compareTo(target) <= 0)
l = mid + 1;
else // nums[mid] > target
r = mid;
}
return l;
}
// 二分查找法, 在一个有序数组arr中, 寻找小于等于target的元素的最大索引
// 如果存在, 则返回相应的索引index
// 否则, 返回 -1
public static int lastLessOrEqual(Comparable[] arr, Comparable target){
if(arr == null)
throw new IllegalArgumentException("arr can not be null.");
int l = -1, r = arr.length - 1;
while(l != r){
int mid = l + (r - l + 1) / 2;
if(arr[mid].compareTo(target) > 0)
r = mid - 1;
else // nums[mid] <= target
l = mid;
}
return l;
}
// 二分查找法, 在一个有序数组arr中, 寻找小于target的元素的最大索引
// 如果存在, 则返回相应的索引index
// 否则, 返回 -1
public static int lastLessThan(Comparable[] arr, Comparable target){
if(arr == null)
throw new IllegalArgumentException("arr can not be null.");
int l = -1, r = arr.length - 1;
while(l != r){
int mid = l + (r - l + 1) / 2;
if(arr[mid].compareTo(target) >= 0)
r = mid - 1;
else // nums[mid] < target
l = mid;
}
return l;
}
}