[PS] 99ํด๋ฝ ์ฝํ ์คํฐ๋ 30์ผ์ฐจ TIL (Find Right Interval)
ํ๊ทธ: 99ํด๋ฝ, PS, TIL, ์ด๋ถํ์, ์ฝ๋ฉํ ์คํธ์ค๋น, ํญํด99
์นดํ ๊ณ ๋ฆฌ: PS
๋ฌธ์
์ค๋ช
๋ฌธ์ ์์ n ๊ฐ์ ์ธํฐ๋ฒ๋ค์ด ์ฃผ์ด์ง๋ค. ๊ฐ ์ธํฐ๋ฒ์ [start, end] ํํ๋ก ์ฃผ์ด์ง๋ฉฐ, start๋ ๊ตฌ๊ฐ์ ์์์ , end๋ ๊ตฌ๊ฐ์ ๋์ ์ ๋ํ๋ธ๋ค.
ํ์ด
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
class Solution {
public int[] findRightInterval(int[][] intervals) {
int n = intervals.length;
int[][] indexArr = new int[n][2];
// ์ธ๋ฑ์ค ์ ์ฅ
for (int i = 0; i < indexArr.length; i++) {
indexArr[i][0] = intervals[i][0]; // start
indexArr[i][1] = i; // index
}
// start ๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ
Arrays.sort(indexArr, (o1, o2) -> Integer.compare(o1[0], o2[0]));
int[] result = new int[n];
for (int i = 0; i < n; i++) {
int end = intervals[i][1];
int search = binarySearch(indexArr, end);
result[i] = search;
}
return result;
}
//
private int binarySearch(int[][] indexArr, int end) {
int left = 0, right = indexArr.length;
while (left < right) {
int mid = left + (right - left) / 2;
int start = indexArr[mid][0];
if (start < end) {
left = mid + 1;
} else {
right = mid;
}
}
return left < indexArr.length ? indexArr[left][1] : -1;
}
}
1
2
intervals = [[3, 4], [2, 3], [1, 2]]
indexArr = [[3, 0], [2, 1], [1, 2]]
๋๊ธ๋จ๊ธฐ๊ธฐ