import java.util.Stack;
import org.junit.Test;
public class solution {
@Test
public void testFunc(){
int[] arr = {13,7,6,12};
int[] res = get(arr);
for(int ele:res){
System.out.print(ele+" ");
}
}
public int[] get(int[] arr){
int[] max=new int[arr.length];
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
for(int i=1;i<arr.length;i++){
int top = stack.peek();
while (!stack.isEmpty() && arr[i]>arr[top]) {
max[top]=arr[i];
stack.pop();
if (!stack.isEmpty()) {
top = stack.peek();
}
}
stack.push(i);
}
while (!stack.isEmpty()) {
int top = stack.pop();
max[top]=-1;
}
return max;
}
}
import org.junit.Test;
public class solution {
@Test
public void testFunc(){
int[] arr = {13,7,6,12};
int[] res = get(arr);
for(int ele:res){
System.out.print(ele+" ");
}
}
public int[] get(int[] arr){
int[] max=new int[arr.length];
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
for(int i=1;i<arr.length;i++){
int top = stack.peek();
while (!stack.isEmpty() && arr[i]>arr[top]) {
max[top]=arr[i];
stack.pop();
if (!stack.isEmpty()) {
top = stack.peek();
}
}
stack.push(i);
}
while (!stack.isEmpty()) {
int top = stack.pop();
max[top]=-1;
}
return max;
}
}
本文介绍了一个使用Java实现的栈应用示例,该示例通过维护一个整数数组并利用栈来更新每个元素对应的下一个更大元素。代码展示了如何用Stack类进行元素的压入和弹出操作,并最终形成结果数组。
471

被折叠的 条评论
为什么被折叠?



