Data structure -- monotone stack structure

The problem solved: In an array, at each position of num, find the value > num that is close to num on the left, and the value > num that is close to num on the right

Time complexity: O(N)

 

Prepare a stack: from the bottom of the stack to the top of the stack, from big to small

Traverse the array, push the elements num in the array into the stack in turn, and ensure that the elements in the stack are larger than num. If num is larger than the elements in the stack, the elements in the stack are popped, and the result of the popped element is recorded, and num is the popped element. The element on the right that is closer to it is greater than it, and the element next to it in the stack is the element that is closer to it and greater than it on the left.

Keep popping until the element in the stack is greater than the element to be pushed, or the stack is empty to stop

When the array is traversed, the elements in the stack are popped out in turn. At this time, the element on the right side of the element they pop up is null, and the element on the left side that is close to it and greater than it is the next element in the stack.

Note: When encountering two identical elements, do not pop up, press the subscripts together, pop up together when popping up, and update their left and right larger than them at the same time

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325292809&siteId=291194637