作者Rushia (早瀬ユウカの体操服 )
標題Re: [閒聊] 每日leetcode
時間2024-10-01 01:35:26
https://leetcode.com/problems/design-a-stack-with-increment-operation/description
1381. Design a Stack With Increment Operation
實作一個可以增加底部k個元素數值的堆疊資料結構。
思路:
1.把遞增值放在索引位置 MIN(stack.size, k),因為堆疊一定從頂部開始拿,所以我們
碰到要遞增的地方的時候(假設為 i),就把遞增值取出來並把遞增值往 i-1 位置的
地方增加,這樣就不用一直去加前面ㄉㄌ
java code:
-----------------------------------------------
class CustomStack {
int maxSize;
int[] arr;
Deque<Integer> stack = new ArrayDeque<>();
public CustomStack(int maxSize) {
this.maxSize = maxSize;
arr = new int[1001];
}
public void push(int x) {
if (stack.size() < maxSize) {
stack.addLast(x);
}
}
public int pop() {
if (stack.isEmpty()) return -1;
int inc = arr[stack.size()];
arr[stack.size()] = 0;
int x = stack.pollLast();
arr[stack.size()] += inc;
return x + inc;
}
public void increment(int k, int val) {
arr[Math.min(k, stack.size())] += val;
}
}
-----------------------------------------------
--
你跟我說這個我有什麼辦法
https://i.imgur.com/wb5zrOy.jpeg
--
※ 發信站: 批踢踢實業坊(ptt.org.tw), 來自: 49.158.191.3 (臺灣)
※ 文章網址: https://ptt.org.tw/Marginalman/M.1727717729.A.E09