2024/11/25 灵茶题单 单调栈
This commit is contained in:
parent
ef5f3e6378
commit
5f49f65c77
|
@ -0,0 +1,27 @@
|
||||||
|
package com.cool.ling_cha_mount.stack;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
|
public class Num503 {
|
||||||
|
public int[] nextGreaterElements(int[] nums) {
|
||||||
|
Stack<Integer> stack = new Stack<>();
|
||||||
|
for (int i = nums.length - 1; i >= 0; i--) {
|
||||||
|
stack.push(nums[i]);
|
||||||
|
}
|
||||||
|
for (int i = nums.length - 1; i >= 0; i--) {
|
||||||
|
while (!stack.isEmpty() && stack.peek() <= nums[i]) {
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
|
int res = stack.isEmpty() ? -1 : stack.peek();
|
||||||
|
stack.push(nums[i]);
|
||||||
|
nums[i] = res;
|
||||||
|
}
|
||||||
|
return nums;
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
public void test(){
|
||||||
|
nextGreaterElements(new int[]{1,2,3,4,3});
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue