조건 : 배열이 오름차순되어 있다.
정의 :
lower bound target이 시작되는 첫번째 index.
upper bound target이 종료되는 index의 +1.
ex)
//1, [2], 2, 2, [3], 4,4,4,4,4,4,4,4,4,4,4,4
upper_bound - lower_bound = target의 개수.
public static void main(String[] args) throws IOException {
int[] arr1 = { 1, 1, 1,1,1,1,1,1,1,1,1,1, 2, 2, 2, 3, 4 };
int[] arr2 = { 1, 2, 2, 2, 3, 4,4,4,4,4,4,4,4,4,4,4,4 };
//1, 1, 1,1,1,1,1,1,1,1,1,1, [2], 2, 2, [3], 4
System.out.println("upper_bound : " + upper_bound(arr1, 2, 0));
System.out.println("lower_bound : " + lower_bound(arr1, 2, 0));
//1, [2], 2, 2, [3], 4,4,4,4,4,4,4,4,4,4,4,4
System.out.println("upper_bound : " + upper_bound(arr2, 2, 0));
System.out.println("lower_bound : " + lower_bound(arr2, 2, 0));
}
private static int lower_bound(int[] a, int t, int s) {
int rt = a.length;
int lt = s;
while (lt < rt) {
int mid = (rt + lt) / 2;
if (t <= a[mid]) {
rt = mid;
} else if (t > a[mid]) {
lt = mid + 1;
}
}
return rt;
}
private static int upper_bound(int[] a, int t, int s) {
int rt = a.length;
int lt = s;
while (lt < rt) {
int mid = (rt + lt) / 2;
if (t >= a[mid]) {
lt = mid + 1;
} else if (t < a[mid]) {
rt = mid;
}
}
System.out.printf("l : %d r : %d\n", lt, rt);
return rt;
}
upper_bound : 15
lower_bound : 12
upper_bound : 4
lower_bound : 1
'PS > BOJ' 카테고리의 다른 글
2632 (0) | 2022.05.05 |
---|---|
7453 (0) | 2022.05.05 |
부분 수열 DFS 기본형태 (0) | 2022.05.05 |
1208 (0) | 2022.05.05 |
1261 (다익스트라 문제) (0) | 2022.05.04 |