PS/LeetCode
[CoderPad Interview] Problem 77 [Easy]
returnzero
2022. 8. 4. 15:37
Problem 77 [Easy]
This problem was asked by Snapchat.
Given a list of possibly overlapping intervals, return a new list of intervals where all overlapping intervals have been merged.
The input list is not necessarily ordered in any way.
For example, given [(1, 3), (5, 8), (4, 10), (20, 25)], you should return [(1, 3), (4, 10), (20, 25)].
//Problem 77 [Easy]
function answer(arr){
const ans=[];
arr.sort((a,b)=>{return a[0]-b[0]});
const [from, to]=arr.shift();
let currentStartPoint=from;
let currentEndPoint=to;
while(arr.length){
const [from, to ]= arr.shift();
if(from>currentEndPoint||to>currentEndPoint){ //1,3 그리고 2,3
ans.push([currentStartPoint,currentEndPoint]);
if(arr.length===0){
ans.push([from,to]);
}
currentStartPoint=from
currentEndPoint=to;
}
}
console.log(ans);
return ans; //[ [ 1, 3 ], [ 4, 10 ], [ 20, 25 ] ]
}
answer([ [1, 3], [5, 8], [4, 10],[20, 25]])
Javasciprt의 sort기능은 매우 강력하다. Python, C, C++, R 통틀어서 제일 효과적이다.