Skip to content

Instantly share code, notes, and snippets.

@shaoshing
Created April 23, 2020 21:34
Show Gist options
  • Save shaoshing/8b4b5827c836b981e0255dd9a0ca91f9 to your computer and use it in GitHub Desktop.
Save shaoshing/8b4b5827c836b981e0255dd9a0ca91f9 to your computer and use it in GitHub Desktop.
Created with Copy to Gist
/**
* @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