给定一个不含有重复值的数组arr,找到每一个i位置左边和右边离i位置最近且值比arr[i]小的位置。返回所有位置相应的信息。
import java.util.Stack;public class MonotonousStack {public static void main(String[] args) {int arr[] = {1,2,3,9,8,7,5,6,4};int res[][] = getNearLessNoRepeat(arr);for (int i = 0; i < res.length; i++) {System.out.println(res[i][0]+" "+res[i][1]);}System.out.println("===================");int arr2[] = {1,6,3,9,5,8,7,5,2,6,4};int res2[][] = getNearLessRepeat(arr2);for (int i = 0; i < res2.length; i++) {System.out.println(res2[i][0]+" "+res2[i][1]);}}// 数组不包含重复值public static int[][] getNearLessNoRepeat(int arr[]){int[][] res = new int[arr.length][2];// 栈存放的是数组arr的位置索引Stack<Integer> stack = new Stack<>();for (int i =0; i < arr.length; i++){while(!stack.isEmpty() && arr[stack.peek()] > arr[i]){// 当栈顶元素比arr[i]大时,就弹出栈int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = i;}stack.push(i);}// 当stack不为空时while(!stack.isEmpty()){int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = -1;}return res;}// 数组包含重复值public static int[][] getNearLessRepeat(int arr[]){int[][] res = new int[arr.length][2];Stack<Integer> stack = new Stack<>();for (int i =0; i < arr.length; i++){while(!stack.isEmpty() && arr[stack.peek()] >= arr[i]){// 当栈顶元素>=arr[i]时,就弹出栈int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = i;}stack.push(i);}// 当stack不为空时while(!stack.isEmpty()){int popIndex = stack.pop();int leftLessIndex = stack.isEmpty() ? -1 : stack.peek();res[popIndex][0] = leftLessIndex;res[popIndex][1] = -1;}for (int i = res.length-1; i >= 0; i--) {int index = res[i][1];if(index != -1 && arr[i] == arr[index]){res[i][1] = res[index][1];}}return res;}
}