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:
1.record(order_id): adds the order_id to the log
2.get_last(i): gets the ith last element from the log. i is guaranteed to be smaller than or equal to N.
Example:
Input: orderIds={3,4,1,6,5,2}, index=3
Output: 6
Approach
C++
#include <bits/stdc++.h>using namespace std;vector<int> circularBuffer;int maxSize;int currIdx;void LogDataStructure(int n){maxSize = n;circularBuffer.resize(n);currIdx = 0;}void record(int orderId){circularBuffer[currIdx] = orderId;currIdx = (currIdx + 1) % maxSize;}int getLast(int i){return circularBuffer[(currIdx - i + maxSize) % maxSize];}int main(){vector<int> orderIds = {3, 4, 1, 6, 5, 2};LogDataStructure(orderIds.size());for (int i = 0; i < orderIds.size(); i++){record(orderIds[i]);}int index = 3;cout << getLast(index);return 0;}
No comments:
Post a Comment