js 实现python的SortedList有序集合

力扣(LeetCode)- 327. 区间和的个数(JavaScript)

这题用到了有序集合,但是js没有这种集合总是超时。手动实现如下。

复制代码
// 默认比较器,处理NaN,规则和Python保持一致:NaN比任何数大,两个NaN相等
function defaultCompare(a, b) {
  if (Number.isNaN(a) && Number.isNaN(b)) return 0;
  if (Number.isNaN(a)) return 1;
  if (Number.isNaN(b)) return -1;
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
}

class SortedList {
    constructor(items = [], options = []) {
        if (options.compare) {
            this.compare = options.compare
        } else {
            this.compare = defaultCompare
        }
        // 内部存储数组,初始就排序
        this._arr = [...items].sort(this.compare);
    }

    bisectLeft(target) {
        let low = 0
        let high = this._arr.length
        while (low < high) {
            const mid = Math.trunc((low + high) / 2)
            if (this.compare(this._arr[mid], target) < 0) {
                low = mid + 1
            } else {
                high = mid
            }
        }
        return low
    }

    bisectRight(target) {
        let low = 0
        let high = this._arr.length
        while (low < high) {
            const mid = Math.trunc((low + high) / 2)
            if (this.compare(this._arr[mid], target) <= 0) {
                low = mid + 1
            } else {
                high = mid
            }
        }
        return low
    }

    add(item) {
        const pos = this.bisectLeft(item);
        this._arr.splice(pos, 0, item);
    }
}

这题解答方法

复制代码
var countRangeSum = function(nums, lower, upper) {
    const len = nums.length;
    let count = 0
    let sum = 0
    const list = new SortedList([0])
    for (let i = 0;i < len;i++) {
        sum += nums[i]
        const left = list.bisectLeft(sum - upper)
        const right = list.bisectRight(sum - lower)
        count += right - left
        list.add(sum)
    }
    return count
};
相关推荐
ikun_文几秒前
Django开启跨域请求
python·pycharm·django
外收内放1 分钟前
Python与AI应用(项目开发实战:AI智能伴侣第三版)
python·学习·ai编程
尾善爱看海4 分钟前
《JavaScript 数组操作全攻略:12 类 API + 30 个实战场景 + 20 个避坑指南》
前端·javascript·面试
别动我齐刘海4 分钟前
ROS2 Jazzy + C++ 实战路线——进阶学习3
c++·人工智能·vscode·python·算法·机器学习·机器人
Bs_MoneyMagnet5 分钟前
基于springboot+vue的非遗物质文化遗产系统的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring·毕业设计·计算机毕业设计
万物智能6 分钟前
波形发生AD9833模块配置—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
java
Logintern097 分钟前
“以一致的顺序获取锁“是预防死锁最核心、最有效的手段
python·postgresql·锁机制
计算机毕设定制辅导-无忧学长19 分钟前
《基于SpringBoot的未成年人健康知识科普平台的设计与实现》
java·开发语言·vue.js·spring boot·未成年人健康知识科普平台
Wang's Blog19 分钟前
Java 项目实战: 外卖平台-数据库环境搭建与十一张表结构解析
java·服务器·redis
OpsEye21 分钟前
为什么你的 Agent 莫名烧钱?聊聊循环调用的兜底方案
javascript·ai编程