給定一個長度為N的整數數列,輸出每個數左邊第一個比它小的數,如果不存在則輸出-1,
輸入格式
第一行包含整數N,表示數列長度,
第二行包含N個整數,表示整數數列,
輸出格式
共一行,包含N個整數,其中第i個數表示第i個數的左邊第一個比它小的數,如果不存在則輸出-1,
資料范圍
1≤N≤1051≤N≤105
1≤數列中元素≤1091≤數列中元素≤109
輸入樣例:
5
3 4 2 7 5
輸出樣例:
-1 3 -1 2 2
思路:用堆疊維護一個單調序列
import java.util.Scanner; import java.util.Stack; public class Main{ static Stack<Integer> sta=new Stack<>(); public static void main(String[] args) { Scanner scan=new Scanner(System.in); int m=scan.nextInt(); while(m-->0){ int num=scan.nextInt(); while(!sta.isEmpty() && sta.peek()>=num) sta.pop(); if(sta.isEmpty()) System.out.print("-1 "); else System.out.print(sta.peek()+" "); sta.push(num); } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/103938.html
標籤:其他
上一篇:829. 模擬佇列
下一篇:關于思科模擬器的 問題
