[Daily Coding Problem] 16. Last N order ids implementation

ぃ、小莉子 提交于 2019-12-28 11:35:00

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 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!