Created
April 23, 2020 21:34
-
-
Save shaoshing/8b4b5827c836b981e0255dd9a0ca91f9 to your computer and use it in GitHub Desktop.
Created with Copy to Gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} intervals | |
* @return {number[]} | |
*/ | |
var findRightInterval = function(intervals) { | |
// collecting and sort tne ends with their index | |
const starts = intervals.map(([start], index) => ({ start, index })).sort((a, b) => a.start - b.start) | |
return intervals.map(([_, end]) => { | |
const startIndex = findMinimumStart(starts, end) | |
return startIndex === -1 ? -1 : starts[startIndex].index | |
}) | |
}; | |
// lower bound | |
function findMinimumStart(starts, target) { | |
let li = 0 | |
let ri = starts.length-1 | |
while(li+1 < ri) { | |
const mi = Math.floor((li+ri)/2) | |
if (starts[mi].start < target) { | |
li = mi | |
} else { | |
ri = mi | |
} | |
} | |
if (starts[ri].start < target || starts[li].start > target) return -1 | |
return starts[li].start >= target ? li : ri | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment