题解 | #单调栈#
单调栈
http://www.nowcoder.com/practice/ae25fb47d34144a08a0f8ff67e8e7fb5
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int一维数组
* @return int二维数组
*/
public int[][] foundMonotoneStack (int[] nums) {
// write code here
int[][] result = new int[nums.length][2];
if(nums == null || nums.length == 0){
return result;
}
Stack<Integer> stack = new Stack<>();
for(int i = 0;i< nums.length; i++){
while(!stack.isEmpty() && nums[stack.peek()] >= nums[i]){
stack.pop();
}
if(stack.isEmpty()){
result[i][0] = -1;
}else{
result[i][0] = stack.peek();
}
stack.push(i);
}
stack.clear();
for(int j = nums.length - 1;j >= 0;j--){
while(!stack.isEmpty() && nums[stack.peek()] >= nums[j]){
stack.pop();
}
if(stack.isEmpty()){
result[j][1]= -1;
}else{
result[j][1] = stack.peek();
}
stack.push(j);
}
return result;
}
}