在 JavaScript 中將新區間插入已排序的區間陣列


在本題中,我們將區間定義為由兩個數字組成的陣列,其中第一個數字始終小於第二個數字。

例如:

[4, 6], [2, 3], [6, 8], [2, 7], [1, 8] are all examples of valid intervals.

假設我們有一個區間陣列,它根據其起始時間(每個區間的第一個元素)排序。

陣列中的區間是不重疊的,這意味著對於任意兩個相鄰區間:

[m, n], [x, y]
m < n < x < y

因此,這個區間陣列的一個例子可以是:

const arr = [[ 2, 4], [5, 7], [9, 10], [13, 17]];

我們需要編寫一個 JavaScript 函式,該函式將這樣一個區間陣列作為第一個引數,並將單個區間作為第二個引數。

然後,該函式應將區間插入到陣列中的正確位置,並保持陣列的不重疊屬性。

如果需要,我們可以合併陣列中的兩個或多個區間,以保持陣列區間不重疊。

例如,如果對於上述區間陣列,我們需要插入的區間是 [6, 13],則輸出應如下所示:

const output = [[2, 4], [5, 17]];

示例

以下是程式碼:

const arr = [[2, 4], [5, 7], [9, 10], [13, 17]];
const interval = [6, 13];
const insertWithin = (arr = [], interval = []) => {
   const res = [];
   let ind = 0;
   while (arr[ind] && arr[ind][1] < interval[0]) {
      res.push(arr[ind]);
      ++ind;
   };
   let start = interval[0];
   let end = interval[1];
   while (arr[ind] && arr[ind][0] <= interval[1]) {
      start = Math.min(start, arr[ind][0]);
      end = Math.max(end, arr[ind][1]);
      ++ind;
   }
   res.push([start, end]);
   while (arr[ind]) {
      res.push(arr[ind]);
      ++ind;
   }
   return res;
};
console.log(insertWithin(arr, interval));

輸出

以下是控制檯輸出:

[[2, 4], [5, 17]]

更新於:2021年1月18日

511 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.