[Algorithm] Circular buffer

You run an e-commerce website and want to record the last N order ids in a log. Implement a data structure to accomplish this, with the following API:

  • record(order_id): adds the order_id to the log
  • get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N.

You should be as efficient with time and space as possible.

It seems like an array would be the perfect fit for this problem. We can just initialize the array to have size N, and index it in constant time. Then, when we record any orders, we can pop off the first order and append it to the end. Getting the ith last order would then just be indexing the array at length - i.

This is one issue with this solution, however: when we have to pop off an element when the array is full, we have to move every other element down by 1. That means record takes O(N) time. How can we improve this?

What we can do to avoid having to moving every element down by 1 is to keep a current index and move it up each time we record something. For get_last, we can simply take current - i to get the appropriate element. Now, both record and get_last should take constant time.

This is actually called Circular buffer:

 

复制代码
function CB_log (total) {
  let current = 0;
  let n = total;
  let logs = [];
  return {
    record (id) {
      logs[current] = id;
      current = (current + 1) % n;
    },
    get_last(i) {
      if (i > n || !i) {
          return null;
      }
      let idx = current - i;
      if (idx >= 0) {
        return logs[idx]
      } else {
        return logs[n - Math.abs(idx)]
      }
    }
  }
}



const log = new CB_log(5);

log.record(41);
log.record(17);
log.record(12);
log.record(78);
log.record(100);//3
log.record(1);//2
log.record(0);//1

console.log(
  log.get_last(4) // 78
)
复制代码

 

posted @   Zhentiw  阅读(256)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-03-20 [Angular] Reactive Form -- FormControl & formControlName, FormGroup, formGroup & formGroupName
2016-03-20 [Angular 2] Using the @Inject decorator
2016-03-20 [WebStrom] Cannot detect file change to trigger webpack re-compile
2016-03-20 [TypeScript] Avoid any type
2016-03-20 [Angular 2] Injecting a Service
2016-03-20 [Angular 2] Event in deep
2015-03-20 [Javascript] Get Started with LeafletJS Mapping
点击右上角即可分享
微信分享提示