使用 Scanner, System.out.println()
运行时间: 7806ms
代码
import java.util.*;
public class Main {
static final int N = 100010;
static int[] stk = new int[N]; // 栈数组
static int tt = -1; // tt指向栈顶元素
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int x = in.nextInt();
while (tt != -1 && stk[tt] >= x)
tt--;
if (tt != -1)
System.out.print(stk[tt] + " ");
else
System.out.print("-1 ");
// 将新元素添加到 stk中
stk[++tt] = x;
}
}
}
使用 BufferReader, BufferWriter
运行时间: 2422ms
代码
import java.io.*;
public class Main {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
static final int N = 100010;
static int[] stk = new int[N]; // 栈数组
static int tt = -1; // tt指向栈顶元素
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(reader.readLine());
String[] s = reader.readLine().split(" ");
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(s[i]);
while (tt != -1 && stk[tt] >= x)
tt--;
if (tt != -1)
log.write(stk[tt] + " ");
else
log.write("-1 ");
// 将新元素添加到 stk中
stk[++tt] = x;
}
// 关闭输入输出流
log.flush();
reader.close();
log.close();
}
}