zoukankan      html  css  js  c++  java
  • [程序员代码面试指南]栈和队列-单调栈结构(单调栈)

    问题描述

    给定一个数组,找到每一个位置左边和右边离它最近的且值比它小的位置,返回一个二维数组表示每个位置对应的两个位置。

    解题思路

    • 使用单调栈,保证栈内元素从栈顶到栈底严格单调递减。
    • 每个元素入出栈一次,时间复杂度O(n)
      具体的,如果x位置被弹出,在栈中位于ta下面的位置的元素就是满足题意的左边元素,当前元素就是满足题意的右边元素。
      若该位置下面无元素,则左边为-1.
      遍历阶段结束后,清算栈中剩下位置,所有此阶段弹出的右边为-1.、

    todo

    处理含重复元素数组的改进方法待做。

    代码

    import java.util.Stack;
    
    public class Main {
    	public static void main(String args[]) {
    		int[] arr= {3,4,1,5,6,2,7};
    		//int[] arr= {3,1,3,4,3,5,3,2,2};
    		int[][] nearPos=nearSmallerNumPos(arr);
    		for(int i=0;i<nearPos.length;++i) {
    			for(int j=0;j<nearPos[0].length;++j) {
    				System.out.print(nearPos[i][j]);
    			}
    			System.out.print("
    ");
    		}
    	}
    	public static int[][] nearSmallerNumPos(int arr[]){
    		int[][] nearPos=new int[arr.length][2];
    		Stack<Integer> stack=new Stack<>();
    		for(int i=0;i<arr.length;++i) {
    			while(!stack.isEmpty()&&arr[stack.peek()]>arr[i]) {//
    				int pos=stack.pop();
    				nearPos[pos][0]=stack.isEmpty()?-1:stack.peek();
    				nearPos[pos][1]=i;//
    			}
    			stack.push(i);//
    		}
    		while(!stack.isEmpty()) {
    			int pos=stack.pop();//
    			nearPos[pos][0]=stack.isEmpty()?-1:stack.peek();
    			nearPos[pos][1]=-1;
    		}
    		return nearPos;
    	}
    }
    
  • 相关阅读:
    luogu P4009 汽车加油行驶问题
    luogu P4015 运输问题
    luogu P2763 试题库问题
    luogu P4011 孤岛营救问题
    luogu P2765 魔术球问题
    linux 网卡
    linux yum错误
    ubuntu登录备注信息
    Ubuntu网卡配置
    linux 走三层内网添加静态路由
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/10865243.html
Copyright © 2011-2022 走看看