先使用最直观的解法:
class CustomStack {
public:
CustomStack(int maxSize) {
m_maxsize = maxSize;
}
void push(int x) {
if(m_elem.size() >= m_maxsize)
return;
m_elem.push(x);
}
int pop() {
if(m_elem.empty())
return -1;
int x = m_elem.top();
m_elem.pop();
return x;
}
void increment(int k, int val) {
stack<int> exchange;
while(!m_elem.empty())
{
int elem = m_elem.top();
m_elem.pop();
exchange.push(elem);
}
while(!exchange.empty())
{
int elem = exchange.top();
exchange.pop();
if(k-- > 0)
elem += val;
m_elem.push(elem);
}
}
private:
int m_maxsize;
stack<int> m_elem;
};
/**
* Your CustomStack object will be instantiated and called as such:
* CustomStack* obj = new CustomStack(maxSize);
* obj->push(x);
* int param_2 = obj->pop();
* obj->increment(k,val);
*/
运行效率:
Runtime: 96 ms, faster than 6.13% of C++ online submissions for Design a Stack With Increment Operation.
Memory Usage: 37.2 MB, less than 6.22% of C++ online submissions for Design a Stack With Increment Operation.
使用差分数组后,代码如下:
class CustomStack {
public:
CustomStack(int maxSize) {
m_size = maxSize;
}
void push(int x) {
if(stack.size() == m_size) return;
stack.push_back(x);
inc.push_back(0);
}
int pop() {
int i = stack.size() - 1;
if(i < 0) return -1;
if(i > 0) inc[i-1] += inc[i];
int elem = stack[i] + inc[i];
stack.pop_back();
inc.pop_back();
return elem;
}
void increment(int k, int val) {
int i = min(k,(int)stack.size()) - 1;
if(i >= 0) inc[i] += val;
}
private:
vector<int> stack;
vector<int> inc;
int m_size;
};
/**
* Your CustomStack object will be instantiated and called as such:
* CustomStack* obj = new CustomStack(maxSize);
* obj->push(x);
* int param_2 = obj->pop();
* obj->increment(k,val);
*/
运行效率:
Runtime: 36 ms, faster than 44.61% of C++ online submissions for Design a Stack With Increment Operation.
Memory Usage: 20.9 MB, less than 68.74% of C++ online submissions for Design a Stack With Increment Operation.