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 }
  • 相关阅读:
    hello world
    first demo
    Mac出现Operation not permitted
    java 获取一个数字中,各个数字出现的次数
    java 判断回文数字
    202001031
    20200103
    华为手机的系列
    java 反向打印一个数字
    java 生成两个数之间的素数
  • 原文地址:https://www.cnblogs.com/lz87/p/10111902.html
Copyright © 2011-2022 走看看