Publish:

ํƒœ๊ทธ: , , , , ,

์นดํ…Œ๊ณ ๋ฆฌ:

img_3.png

๋ฌธ์ œ

๋ฌธ์ œ ๋งํฌ

img_3.png

์„ค๋ช…

๋ฌธ์ œ์—์„œ 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]]
๋ฐฉ๋ฌธํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋Œ“๊ธ€,์ง€์ ,ํ”ผ๋“œ๋ฐฑ ์–ธ์ œ๋‚˜ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค๐Ÿ˜Š

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ