首页 > web前端 > js教程 > 正文

两指针 - 使用 Javascript 的通用时隙算法

PHPz
发布: 2024-08-30 18:31:45
原创
1071 人浏览过

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学习者快速成长!