1,常规的想法是用两个指针,1个指向要判断的元素,另一个找到大于此元素的元素下标
2,但这个算法的时间复制度是O(n^2)
3,我们可以使用栈来解决此类问题
4,便利元素,当元素小于栈顶元素时,元素进栈;
5,当元素大于栈顶元素时,则计算栈顶元素与当前元素的距离
6,如此时间复制度为O(n)
import java.util.*; public class Client { public static void main(String[] args) { // 0 1 2 3 4 5 6 7 int[] templates = {23,24,25,21,19,22,26,23}; int[] wendu = wendu(templates); System.out.println(Arrays.toString(wendu)); } static int[] wendu(int[] templates ) { int[] result = new int[templates.length]; Stack<Integer> stack = new Stack<>();// 保存的是数组的下标 for (int i = 0; i < templates.length; i++) { if(stack.isEmpty() ){ stack.push(i); }else { Integer peek = stack.peek(); if(templates[i] <= templates[peek]){ stack.push(i); }else {// 比栈顶元素大 while (!stack.isEmpty()){ Integer index = stack.pop(); if(templates[i] > templates[index]){ result[index] = i - index; }else { stack.push(index); break; } } stack.push(i); } } } return result; } }