[Algorithm] Circular buffer

该博客围绕电商网站记录最后N个订单ID的需求,探讨合适的数据结构。先提出用数组实现,但数组满时弹出元素需O(N)时间。后提出通过维护当前索引避免元素移动,实现记录和获取操作的常数时间复杂度,此结构为循环缓冲区。

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
)

 

转载于:https://www.cnblogs.com/Answer1215/p/10562518.html

/work/pcl-cross-compile/src/boost$ ls /work/pcl-cross-compile/install/boost/include/ algorithm dynamic_bitset.hpp make_unique.hpp qvm throw_exception.hpp align enable_shared_from_this.hpp math qvm.hpp timer aligned_storage.hpp exception math_fwd.hpp qvm_lite.hpp timer.hpp align.hpp exception_ptr.hpp move random token_functions.hpp archive foreach_fwd.hpp mpi random.hpp token_iterator.hpp asio foreach.hpp mpi.hpp range tokenizer.hpp asio.hpp format mpl range.hpp tti assign format.hpp multi_array rational.hpp tuple assign.hpp functional multi_array.hpp redis type_erasure call_traits.hpp functional.hpp multi_index redis.hpp type_index cerrno.hpp fusion multi_index_container_fwd.hpp regex type_index.hpp charconv geometry multi_index_container.hpp regex_fwd.hpp typeof charconv.hpp geometry.hpp multiprecision regex.h type_traits circular_buffer gil nondet_random.hpp regex.hpp type_traits.hpp circular_buffer_fwd.hpp gil.hpp none.hpp safe_numerics units circular_buffer.hpp graph none_t.hpp scoped_array.hpp unordered cobalt heap nowide scoped_ptr.hpp unordered_map.hpp cobalt.hpp histogram numeric scope_exit.hpp unordered_set.hpp compressed_pair.hpp histogram.hpp operators.hpp serialization url concept hof operators_v1.hpp shared_array.hpp url.hpp concept_archetype.hpp hof.hpp optional shared_ptr.hpp utility concept_check icl optional.hpp signals2 utility.hpp concept_check.hpp interprocess parameter signals2.hpp uuid config intrusive pending smart_ptr uuid.hpp config.hpp intrusive_ptr.hpp phoenix smart_ptr.hpp variant container io phoenix.hpp sort variant2 context io_fwd.hpp pointer_cast.hpp spirit variant2.hpp convert json pointer_to_other.hpp spirit.hpp variant.hpp convert.hpp json.hpp polygon stacktrace version.hpp cregex.hpp leaf pool stacktrace.hpp vmd cstdfloat.hpp leaf.hpp predef statechart wave cstdint.hpp limits.hpp predef.h static_assert.hpp wave.hpp cxx11_char_types.hpp locale program_options static_string weak_ptr.hpp date_time locale.hpp program_options.hpp static_string.hpp winapi date_time.hpp local_function progress.hpp stl_interfaces xpressive describe local_function.hpp property_map system yap describe.hpp lockfree proto system.hpp detail logic ptr_container test dynamic_bitset make_default.hpp python thread dynamic_bitset_fwd.hpp make_shared.hpp python.hpp thread.hpp uidq8326@hzh27145u:/work/pcl-cross-compile/src/boost$ ./b2 install toolset=gcc architecture=arm address-model=64 \--prefix=/work/pcl-cross-compile/install/boost -j$(nproc) Performing configuration checks - default address-model : 64-bit [1] - default architecture : arm [1] - symlinks supported : yes error: Unable to find file or target named error: '/boost/headers' error: referred to from project at error: 'libs/date_time/build'
08-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值