给定一个不含有重复值的数组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;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.