[php] test

Viewer

  1. function foo(intervals) {
  2.   if (intervals.length === 1) return intervals;
  3.   intervals.sort((a, b) => a[0] - b[0]);
  4.   let current = intervals[0];
  5.   const result = [current];
  6.   for (let i = 1; i < intervals.length; i += 1) {
  7.     const currentRight = current[1];
  8.     const [nextLeft, nextRight] = intervals[i];
  9.     if (currentRight >= nextLeft) {
  10.       current[1] = Math.max(currentRight, nextRight);
  11.     } else {
  12.       result.push(intervals[i]);
  13.       current = intervals[i];
  14.     }
  15.   }
  16.   return result;
  17. }
  18.  
  19. console.log(
  20.   foo([[0, 3], [6, 10]]),
  21.   foo([[0, 5], [3, 10]]),
  22.   foo([[0, 5], [2, 4]]),
  23.   foo([[7, 8], [3, 6], [2, 4]]),
  24.   foo([[3, 6], [3, 4], [15, 20], [16, 17], [1, 4], [6, 10], [3, 6]])
  25. )
  26.  

Editor

You can edit this paste and save as new:


File Description
  • test
  • Paste Code
  • 10 Aug-2022
  • 723 Bytes
You can Share it: