Open super2bai opened 6 years ago
你这种实现跟 @大菠萝 一样,只是粗鲁地实现了题意,但是 get_max 的效率还有待提升。
贴一波PPPPPPPP大佬的Java版本。
static Queue<Integer> q = new LinkedList<Integer>();
static Deque<Integer> d = new LinkedList<Integer>();
public static void push(int elem) {
q.offer(elem);
while (d.peekLast() != null && d.peekLast() < elem)
d.pollLast();
d.offerLast(elem);
}
public static int pop() {
if (q.peek() == null)
return -1;
int res = q.poll();
if (res == d.peekFirst())
d.pollFirst();
return res;
}
public static int get_max() {
if (d.peekLast() == null)
return -1;
return d.peekFirst();
}
public static void main(String[] args) throws java.lang.Exception {
Scanner sc = new Scanner(System.in);
while (true) {
String input = sc.nextLine();
String cmd[] = input.split(" ");
if ("push".equals(cmd[0])) {
int arg = Integer.valueOf(cmd[1]).intValue();
push(arg);
System.out.println("None");
} else if ("pop".equals(cmd[0])) {
System.out.println(pop());
} else if ("get_max".equals(cmd[0])) {
System.out.println(get_max());
}
}
}
Question_ID: Q002
Language: Java
Time Cost: 30mins
Time Complexity: O(n)
Solution
My Code