找出数组中每个数的右边第一个比它大的数或之间有多少数(单调栈问题)

题目:给出一组数,找出数组中每个数的右边第一个比它大的数

分析:

利用单调栈,从左至右依次压入数据的索引(若直接压数,则还需要一个数组保存栈中元素所对应的数组位置)

当当前元素小于等于栈顶的索引所对应的数组的值,入栈当前索引,否则将栈顶索引出栈,并在栈顶索引所对应的res数组中记录下当前的值。

到最后再检查栈中剩余元素,代表剩余元素右边没有比它大的值,在res对应位置赋值为-1

import java.util.Stack;

public class FindRightMax {
	public static void main(String[] arg) {
		int array[]=new int[] {1,5,3,6,4,8,9,10};
		int res[]=findMax(array);
		for(int num:res) {
			System.out.println(num);
		}
		
	}
	public static int[] findMax(int[] array) {
		int len =array.length;
		Stack<Integer> st = new Stack<Integer>();
		int res[]=new int[len];
		int i=0;
		while(i<len) {
			if(st.isEmpty()||array[i]<=array[st.peek()]) {
				st.push(i);
				i++;
			}else {
				res[st.pop()]=array[i];
				
			}
		}
		while(!st.isEmpty()) {
			res[st.pop()]=-1;
		}
		return res;
	}

}

还有一种问题是求数组中每个数的右边第一个比它大的数之间有多少数,只需要在res中记录当前元素索引与栈顶元素索引的差,最后的残留在栈里的元素可以把对应的res数组设置为-1或者len-st.pop(即右边有多少比当前数小的数,比如牛的视野问题https://blog.csdn.net/Broken_Wave/article/details/82389920

猜你喜欢

转载自blog.csdn.net/Broken_Wave/article/details/82390882
今日推荐