【发布时间】:2021-07-04 15:16:22
【问题描述】:
我试图解决一个问题,它被描述为 -> 给定一个数组 A,为数组中的每个元素 A[i] 找到下一个更大的元素 G[i]。元素 A[i] 的下一个更大元素是数组 A 中 A[i] 右侧的第一个更大元素。对于不存在更大元素的元素,将下一个更大元素视为 -1。
public class Solution {
public ArrayList<Integer> nextGreater(ArrayList<Integer> A) {
Stack<Integer> stk = new Stack<>();
if (A.size() == 1)
{
ArrayList<Integer> ans= new ArrayList<>();
ans.add(0,-1);
return ans;
}
ArrayList<Integer> ans= new ArrayList<>(A.size());
ans.add(A.size()-1,-1); //error ->Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 0
stk.push(0);
for(int i=1;i<A.size()-1;i++){
while(!stk.isEmpty()&&A.get(i)>A.get(stk.peek())){
ans.add(stk.pop(),A.get(i));
// stk.pop();
}
stk.push(i);
}
return ans;
}
}
但是在解决这个问题时,我不明白为什么在数组列表中的位置 A.size()-1 添加 -1 时出现错误,其中 A : [ 34, 35, 27, 42, 5, 28, 39, 20, 28]
【问题讨论】:
标签: java arraylist runtime-error indexoutofboundsexception