在 JavaScript 中找出區間陣列的交集


問題

JavaScript 函式接受兩個陣列 arr1 和 arr2,這些陣列是按段排列且按順序排序的。

閉區間 [a, b](其中 a <= b)表示一組實數 x,其中 a <= x <= b。

兩個閉區間的交集是一組實數,該集合要麼為空,要麼可以表示為閉區間。例如,[1, 3] 和 [2, 4] 的交集是 [2, 3])。我們的函式應該返回這兩個區間陣列的交集。

例如此輸入:

const arr1 = [[0,2],[5,10],[13,23],[24,25]];
const arr2 = [[1,5],[8,12],[15,24],[25,26]];

那麼輸出應該是:

const output = [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]];

示例

程式碼如下:

 即時演示

const arr1 = [[0,2],[5,10],[13,23],[24,25]];
const arr2 = [[1,5],[8,12],[15,24],[25,26]];
const findIntersection = function (A, B) {
   const res = []
   let i = 0
   let j = 0
   while (i < A.length && j < B.length) {
      const [a, b] = A[i]
      const [c, d] = B[j]
      const lo = Math.max(a, c)
      const hi = Math.min(b, d)
      if (lo <= hi) {
         res.push([Math.max(a, c), Math.min(b, d)])
      }
      if (b < d) {
         i++
      } else {
         j++
      }
   }
   return res
};
console.log(findIntersection(arr1, arr2));

輸出

控制檯中的輸出:

[
   [ 1, 2 ],
   [ 5, 5 ],
   [ 8, 10 ],
   [ 15, 23 ],
   [ 24, 24 ],
   [ 25, 25 ] 
]

更新於:09-Apr-2021

449 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告