8 lines Java Using Binary Search of Arrays


  • 0
    W
    public int[] findRightInterval(Interval[] intervals) {
      Map<Integer, Integer> map = new HashMap<>(intervals.length, 1f);
      int[] starts = new int[intervals.length], result = new int[intervals.length];
      for (int i = 0; i < intervals.length; map.put(intervals[i].start, i++))
        starts[i] = intervals[i].start;
      Arrays.sort(starts);
      for (int i = 0, idx; i < intervals.length; i++)
        result[i] = (idx = Arrays.binarySearch(starts, intervals[i].end)) >= 0 ? map.get(starts[idx]) : (idx = -(++idx)) == intervals.length ? -1 : map.get(starts[idx]);
      return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.