-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBisectTemplate.java
More file actions
139 lines (128 loc) · 3.64 KB
/
BisectTemplate.java
File metadata and controls
139 lines (128 loc) · 3.64 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package com.fqh;
/**
* @Author: vq
* @Date: 2023/12/15 15:15
* @Version V1.0
*/
import java.util.List;
/**
* 二分搜索模板
*/
public class BisectTemplate {
/**
* 返回 `target` 在 `a` 中最左边的插入位置。
* 存在多个相同的值时,返回最左边的位置。
* @param a 一维数组
* @param target 搜索的值
* @return
*/
public static int bisectLeft(int[] a, long target) {
int left = 0, right = a.length - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (a[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
/**
* 返回 `target` 在 `a` 中最右边的插入位置。
* 存在多个相同的值时,返回最右边的位置。
* @param a 一维数组
* @param target 搜索的值
* @return
*/
public static int bisectRight(int[] a, long target) {
int left = 0, right = a.length - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (a[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
/**
* 返回 `target` 在 `a` 中最左边的插入位置。
* a = [start, end, score]
* @param a 二维数组
* @param target 搜索的值
* @param key 搜索的key
* @return
*/
public static int bisectLeft1(int[][] a, long target, int key) {
int left = 0, right = a.length - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (a[mid][key] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
/**
* 返回 `target` 在 `a` 中最右边的插入位置。
* a = [start, end, score]
* @param a 二维数组
* @param target 搜索的值
* @param key 搜索的key
* @return
*/
public static int bisectRight1(int[][] a, long target, int key) {
int left = 0, right = a.length - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (a[mid][key] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
/**
* 返回 `target` 在 `a` 中最左边的插入位置。
* 存在多个相同的值时,返回最左边的位置。
* @param a list集合
* @param target 搜索的值
* @return
*/
public static int bisectLeft2(List<Integer> a, long target) {
int left = 0, right = a.size() - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (a.get(mid) < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
/**
* 返回 `target` 在 `a` 中最右边的插入位置。
* 存在多个相同的值时,返回最右边的位置。
* @param a list集合
* @param target 搜索的值
* @return
*/
public static int bisectRight2(List<Integer> a, long target) {
int left = 0, right = a.size() - 1;
while (left <= right) {
int mid = (left + right) >> 1;
if (a.get(mid) <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
}