Skip to content

Commit d4b74eb

Browse files
committed
modify code
1 parent ef85606 commit d4b74eb

File tree

1 file changed

+18
-18
lines changed

1 file changed

+18
-18
lines changed

src/class26/Code01_SumOfSubarrayMinimums.java

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
package class26;
22

3-
import java.util.Stack;
4-
53
// 测试链接:https://leetcode.com/problems/sum-of-subarray-minimums/
64
// subArrayMinSum1是暴力解
75
// subArrayMinSum2是最优解的思路
86
// sumSubarrayMins是最优解思路下的单调栈优化
7+
// Leetcode上不要提交subArrayMinSum1、subArrayMinSum2方法,因为没有考虑取摸
98
// Leetcode上只提交sumSubarrayMins方法,时间复杂度O(N),可以直接通过
109
public class Code01_SumOfSubarrayMinimums {
1110

@@ -71,8 +70,9 @@ public static int[] rightNearLess2(int[] arr) {
7170
}
7271

7372
public static int sumSubarrayMins(int[] arr) {
74-
int[] left = nearLessEqualLeft(arr);
75-
int[] right = nearLessRight(arr);
73+
int[] stack = new int[arr.length];
74+
int[] left = nearLessEqualLeft(arr, stack);
75+
int[] right = nearLessRight(arr, stack);
7676
long ans = 0;
7777
for (int i = 0; i < arr.length; i++) {
7878
long start = i - left[i];
@@ -83,34 +83,34 @@ public static int sumSubarrayMins(int[] arr) {
8383
return (int) ans;
8484
}
8585

86-
public static int[] nearLessEqualLeft(int[] arr) {
86+
public static int[] nearLessEqualLeft(int[] arr, int[] stack) {
8787
int N = arr.length;
8888
int[] left = new int[N];
89-
Stack<Integer> stack = new Stack<>();
89+
int size = 0;
9090
for (int i = N - 1; i >= 0; i--) {
91-
while (!stack.isEmpty() && arr[i] <= arr[stack.peek()]) {
92-
left[stack.pop()] = i;
91+
while (size != 0 && arr[i] <= arr[stack[size - 1]]) {
92+
left[stack[--size]] = i;
9393
}
94-
stack.push(i);
94+
stack[size++] = i;
9595
}
96-
while (!stack.isEmpty()) {
97-
left[stack.pop()] = -1;
96+
while (size != 0) {
97+
left[stack[--size]] = -1;
9898
}
9999
return left;
100100
}
101101

102-
public static int[] nearLessRight(int[] arr) {
102+
public static int[] nearLessRight(int[] arr, int[] stack) {
103103
int N = arr.length;
104104
int[] right = new int[N];
105-
Stack<Integer> stack = new Stack<>();
105+
int size = 0;
106106
for (int i = 0; i < N; i++) {
107-
while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
108-
right[stack.pop()] = i;
107+
while (size != 0 && arr[stack[size - 1]] > arr[i]) {
108+
right[stack[--size]] = i;
109109
}
110-
stack.push(i);
110+
stack[size++] = i;
111111
}
112-
while (!stack.isEmpty()) {
113-
right[stack.pop()] = N;
112+
while (size != 0) {
113+
right[stack[--size]] = N;
114114
}
115115
return right;
116116
}

0 commit comments

Comments
 (0)