力扣1146 快照数组

思路:初始时,使用的思路是对于每个快照的数组都进行一次副本保存,但是提交后是时间超出。因此基于 灵神. - 力扣(LeetCode) 的思路不构建数组,而是保存每个数组位置set的记录,记录采用的是键值对的形式,键为当前快照号,值为传递过来需要修改的val;这样构造函数、set以及snap方法都可以比较精简的得到解决。

对于get方法,若没有构建数组存储每个时刻的数据而是直接记录版本更新情况的话,在二分查找时所检索的不是等于当前snap_id的记录,而是需要找到索引list中小于snap_id的第一个元素(因为同一个index出,可以有多个快照号相同的记录);因此二分查找使用红蓝染色法,返回left。

java 复制代码
class SnapshotArray {
    // 快照编号
    int snapidx;
    Map<Integer, List<int[]>> map = new HashMap<>();

    public SnapshotArray(int length) {
        // 定位快照编号
        snapidx = 0;
        // arr = new int[length];
        // 构建map,提前为每个索引建立好历史记录列表
        for(int i=0; i<length; i++){
            List<int[]> list = new ArrayList<>();
            map.put(i, list);
        }
    }
    
    public void set(int index, int val) {
        // 当前版本的数据更新
        // arr[index] = val;
        // 增加一条记录
        List<int[]> list = map.get(index);
        list.add(new int[]{snapidx, val});  // list内加入的元素总是按照时间的先后往其中加入的
        map.put(index, list);
    }
    
    public int snap() {
        snapidx++;
        return snapidx-1;
    }
    
    public int get(int index, int snap_id) {
        // 获取到当前的索引位置的历史版本
        List<int[]> list = map.get(index);
        // 本质上可以通过遍历来实现,使用二分查找加快查找的速度
        int idx = binarysearch(list, snap_id);
        return idx<0? 0:list.get(idx)[1];
    }

    public int binarysearch(List<int[]> list, int snapid){
        // 红蓝染色法的二分查找
        int left = -1;
        int right = list.size();
        while(left + 1 != right){
            int mid = left + (right-left)/2;
            if(list.get(mid)[0] <= snapid)
                left = mid;
            else
                right = mid;
        }

        return left;

    }
}

/**
 * Your SnapshotArray object will be instantiated and called as such:
 * SnapshotArray obj = new SnapshotArray(length);
 * obj.set(index,val);
 * int param_2 = obj.snap();
 * int param_3 = obj.get(index,snap_id);
 */
相关推荐
Zucker n7 小时前
文献发现、课题组织与证据可追溯的论文阅读。
论文阅读·windows·ubuntu
flyingonpine1 天前
PowerShell脚本数字签名实战:自签名证书、代码签名与信任链验证
windows·信任链
goehou1 天前
让 AI 替我操作这台电脑,先把手能伸多远定下来
windows·自动化·权限管理·ai agent
公子小六1 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
2601_967987372 天前
安装 Redis 或 Redis Stack
linux·windows·redis·macos·安装
xbzb2 天前
自定义 yum 软件源:Linux 上 createrepo,Windows 上纯 Python 也能造
linux·运维·windows·python·yum·createrepo
武雄(小星Ai)2 天前
Ollama报llama-server binary not found排坑实录:服务活着引擎没了
人工智能·windows·大模型·ollama·排坑
叼烟扛炮3 天前
[LangChain] 学习笔记(06):突破大模型限制——结构化输出(Structured Output)
windows·笔记·学习·langchain
Thneonl3 天前
桌宠穿透不是一行 SetWindowLong
windows·程序员
艺杯羹4 天前
Windows原生软件锁设计:从暴力杀进程丢数据到零轮询事件驱动架构
windows·系统架构·开源·开源软件·内存管理·开源协议