An application of monotonic stack
A coding problem is shown as follows:
"Given an array of non-positive integers, for each element, find the nearest greater integer on its right. If no such integer exists, mark with -1.
Sample input: [8,3,1,4,9,7,5,6], expected output: [9,4,4,9,-1,-1,6,-1]. "
Solution: solve this problem with a monotonically decreasing stack. Scan the array from left to right and maintain a monotonically decreasing stack. If the current integer is smaller than the stack top, push its index to the stack, otherwise pop the stack until the top is greater or equal to the current one, in the meantime update the result. After scanning, the indices that are still in the stack have no greater element on their right, put -1 in their position.
Code is shown below:
public static int[] rightNearestGreaterNum(int[] nums) { int[] res=new int[nums.length]; Stack<Integer> s=new Stack<Integer>(); for(int i=0;i<nums.length;i++) { while(!s.empty() && nums[i]>nums[s.peek()]) res[s.pop()]=nums[i]; s.push(i); } while(!s.empty())res[s.pop()]=-1; return res; }