如:
有数组arr = {3,5,7,2,4}
从第一个位置 index = 0开始, arr[0]= 3,左侧没有数值,则左侧-1代表无值;右侧arr[1] = 5比arr[0] = 3 大,不符合,arr[2] = 7 ,比arr[0]=3大,不符合,arr[3] = 2 ,比arr[0]=3小,符合,所以results[0] = (-1, 3);
arr[1] = 5, 左侧arr[0] = 3比它小,符合; 右侧 arr[3] = 2,比它小,所以 results[1] = (0, 3);
arr[2] = 7, 左侧arr[1] = 5 比它小,符合; 右侧arr[3] = 2, 比它小,符合,所以results[2] = (1, 3);
arr[3] = 2, 左侧没有比它小的;右侧也没有比它小的,所以, results[3] = (-1, -1);
arr[4] = 4, 左侧arr[3] = 2,比它小; 右侧没有数了,所以, result[4] = (3, -1);
所以汇总的结果就是:
(-1,3),(0,3),(1,3),(-1,-1),(3,-1)
代码:
package com.me.study1;
import java.util.Stack;
public class StudyOne {
public static void main(String[] args) {
// 输入数组
int [] array = new int[]{3,5,7,2,4};
// 使用栈来处理
Stack<Integer> stack = new Stack<Integer>();
Point [] results = new Point[array.length];
for (int i = 0; i < array.length; i++) {
if (!stack.isEmpty() && array[stack.lastElement()] > array[i]) {
int index;
while (!stack.isEmpty() && array[index = stack.lastElement()] > array[i]) {
results[index] = new Point(stack.isEmpty()? -1 : stack.lastElement(), i);
stack.pop();
}
}
stack.push(i);
}
while (!stack.isEmpty()) {
int index = stack.pop();
results[index] = new Point(stack.isEmpty() ? -1 : stack.lastElement(), -1);
}
for (int i = 0; i < results.length; i++) {
System.out.println(results[i].x + ", " + results[i].y);
}
}
public static class Point {
public int x;
public int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
运行效果:
Q.E.D.