zoukankan      html  css  js  c++  java
  • [Daily Coding Problem] 16. Last N order ids implementation

    This problem was asked by Twitter.

    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.

    Implementing a circular buffer suffices the requirement. It takes O(1) to record and get last ith. 

     1 public class LogDataStructure {
     2     private int maxSize;
     3     private int[] circularBuffer;
     4     private int currIdx;
     5         
     6     public LogDataStructure(int n) {
     7         this.maxSize = n;
     8         this.circularBuffer = new int[n];
     9         this.currIdx = 0;
    10     }
    11 
    12     public void record(int orderId) {
    13         circularBuffer[currIdx] = orderId;
    14         currIdx = (currIdx + 1) % maxSize;
    15     }
    16     
    17     public int getLast(int i) {
    18         return circularBuffer[(currIdx - i + maxSize) % maxSize];
    19     }
    20 }
  • 相关阅读:
    学习CSS定位(布局)
    XSLT
    CSS模型框学习笔记
    XMLDOM复习
    XMLDOM之浏览器差异
    HTMLDOM入门
    学习二级纵向菜单两步走
    Xpath很全的学习地点,不看后悔
    LinQ To XML
    收集的一些零散代码
  • 原文地址:https://www.cnblogs.com/lz87/p/10111902.html
Copyright © 2011-2022 走看看