Java - monotonic stack

The role of the monotone stack is to find the smaller value closest to the element in an array (the minimum value on the left and the minimum value on the right)

First maintain a strict stack structure from small to large

Iterate through the array from the beginning 

(1) If the element is added and does not meet the requirements from small to large (this element is smaller than the topmost element), the topmost element is popped up until it is satisfied from small to large. When a value is popped up, the element that pops up is the smaller element on its right value, its next one is the smaller value on the left

(2) If this element is equal to the top layer, "merge" this element with the top layer element

(3) If it is larger than the top element, add it directly

If all elements are traversed at the end and there are still elements in the stack, it can only mean that there is no smaller value on the right side of this element. If an element is popped out at the bottom, it means that there is no smaller value on the left side of it.


public static int [][] MonotonousStack(int [] arr,int w) {
	 Stack<List<Integer>> stack = new Stack<List<Integer>>();
	 int [][] result = new int[arr.length][2];
	 for(int i = 0;i<arr.length-1;i++) {
		 while(!stack.empty()&&arr[i]>stack.peek().get(stack.peek().size() - 1)) {
			 List<Integer> list = stack.pop();
			 int leftLessIndex = stack.isEmpty() ? -1 : stack.peek().get(stack.peek().size() - 1);//如果栈为空了说明下面没有数了
				for (Integer popi : list) {
					result[popi][0] = leftLessIndex;
					result[popi][1] = i;
				}
		 }
		 if (!stack.isEmpty() && arr[stack.peek().get(0)] == arr[i]) {
				stack.peek().add(Integer.valueOf(i));
			} else {
				ArrayList<Integer> list = new ArrayList<>();
				list.add(i);
				stack.push(list);
			}//所以每一个list还是要自己初始化的
	 }
	 return result;
}

(The indescribable annotations are for your own understanding......)

Guess you like

Origin blog.csdn.net/chara9885/article/details/130259406