Open patrickz93 opened 3 years ago
public int pop() {
if(currentIndex == -1) {
return -1;
}
int val = arr[currentIndex] + incrArr[currentIndex];
if (currentIndex > 0) {
incrArr[currentIndex - 1] += incrArr[currentIndex];
}
incrArr[currentIndex] = 0;
currentIndex--;
return val;
}
public void increment(int k, int val) {
int incrArrLastIndex = k-1 >= currentIndex ? currentIndex : k-1;
if(incrArrLastIndex > -1) {
incrArr[incrArrLastIndex] += val;
}
}
思路
用数组模拟栈,用一个变量记录数组末尾元素的下标,实现入栈、出栈。 使用另外一个数组用来记录栈底n个元素的增加值情况,元素出栈时,两个数组相应位置上的元素清零,末尾元素下标做减法。 只有当元素出栈的时候,获取该下标所有的incr结果,达到O(1)。
代码
复杂度分析