1381. 设计一个支持增量操作的栈
作者:互联网
用栈实现
import java.util.Stack;
public class Algorithm {
public static void main(String[] args) {
CustomStack myStack = new CustomStack(5);
for (int i = 0; i < 5; i++) {
myStack.push(i);
}
myStack.increment(2, 10);
for (int i = 0; i < 5; i++) {
System.out.println(myStack.pop());
}
}
}
class CustomStack {
Stack<Integer> stack;
int maxSize;
public CustomStack(int maxSize) {
stack = new Stack();
this.maxSize = maxSize;
}
public void push(int x) {
if (stack.size() < maxSize) {
stack.push(x);
}
}
public int pop() {
return stack.isEmpty() ? -1 : stack.pop();
}
public void increment(int k, int val) {
if (!stack.isEmpty()) {
Stack<Integer> temStack = new Stack<>();
/**
* 使用辅助栈,将元素全部转移,再按k个数进行加值
*/
while (stack.size() > 0) {
temStack.push(stack.pop());
}
if (temStack.size() <= k) {
while (temStack.size() > 0) {
stack.push(temStack.pop() + val);
}
}
else {
while (temStack.size() > 0) {
if (stack.size() < k) {
stack.push(temStack.pop() + val);
} else {
stack.push(temStack.pop());
}
}
}
}
}
}
用数组实现
public class Algorithm {
public static void main(String[] args) {
CustomStack myStack = new CustomStack(5);
for (int i = 0; i < 5; i++) {
myStack.push(i);
}
myStack.increment(2, 10);
for (int i = 0; i < 5; i++) {
System.out.println(myStack.pop());
}
}
}
class CustomStack {
int[] array;
int tem[];
int top;
public CustomStack(int maxSize) {
/**
* top为栈顶位置加一
*/
top = 0;
/**
* 使用两个数组实现,元素值改变时先不动元素
* 用辅助数组存放要改变元素的最后一个位置,和要改变的值
* 当取走一个被改变的元素后,将位置减一
*/
array = new int[maxSize];
tem = new int[maxSize + 1];
}
public void push(int x) {
if (top < array.length) {
array[top] = x;
top++;
}
}
public int pop() {
if (top == 0){
return -1;
}
int res = array[top - 1];
/**
* 辅助数组多一个空间
* 当辅助数组对应的栈顶位置不为零时,说明这个元素增值了,该位置的元素就是增量
* 加上以后,再将增量赋值给前一个位置,也就是等到pop时再增,否则不动
*/
if (tem[top] != 0) {
res += tem[top];
/**
* 注意这个+=
* 因为可能有多次增量,所以值要累加
*/
tem[top - 1] += tem[top];
tem[top] = 0;
}
top--;
return res;
}
public void increment(int k, int val) {
/**
* 有增量时,只记录最后一个变化元素的索引和增量
* 其前面的元素暂时不增加
*/
tem[Math.min(k, top)] += val;
}
}
https://leetcode-cn.com/problems/design-a-stack-with-increment-operation/
标签:int,top,pop,1381,public,增量,push,设计,stack 来源: https://www.cnblogs.com/taoyuann/p/15410664.html