首頁 > web前端 > js教程 > 主體

兩個指標 - 使用 Javascript 的通用時隙演算法

PHPz
發布: 2024-08-30 18:31:45
原創
1070 人瀏覽過

Two Pointer - Common Time Slot Algorithm Using Javascript

當在 2 個人之間尋找共同位置時出現問題。

您可以使用 2 指標技巧來找出答案。

function availableDuration(slots1, slots2, d) {
    let i = 0;
    let j = 0;

    while (i < slots1.length && j < slots2.length) {
        // Finding the boundaries of the intersection, or the common slot
        const left = Math.max(slots1[i][0], slots2[j][0]);
        const right = Math.min(slots1[i][1], slots2[j][1]);
        if (right - left >= d) {
            return [left, left + d];
        }
        // Always move the pointer of the slot that ends earlier
        if (slots1[i][1] < slots2[j][1]) {
            i++;
        } else {
            j++;
        }
    }
    return [];
}

// Example usage
const slots1 = [[10, 50], [60, 120], [140, 210]];
const slots2 = [[0, 15], [60, 70]];
const d = 8;
const result = availableDuration(slots1, slots2, d);
console.log("Earliest common time slot:", result);

// Earliest common time slot: [ 60, 68 ]

登入後複製

參考

更多詳細資訊請查看
https://www.geeksforgeeks.org/meeting-scheduler-for-two-persons/

以上是兩個指標 - 使用 Javascript 的通用時隙演算法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!