Min Queue
题目:
跟min stack一样,实现一个queue,然后O(1) 复杂度来获得这个queue里面的最小元素。
题目分析:
先实现一个stack看一下原理。在做minQueue的时候,当min改变了的时候需要把当前所有的元素从queue里面poll出来。
代码:
min stack:
跟min stack一样,实现一个queue,然后O(1) 复杂度来获得这个queue里面的最小元素。
题目分析:
先实现一个stack看一下原理。在做minQueue的时候,当min改变了的时候需要把当前所有的元素从queue里面poll出来。
代码:
min stack:
Stack<Integer> stack = new Stack<>(); int min = Integer.MAX_VALUE; public MinStack() { } public void push(int x) { if(x <= min){ stack.push(min); min = x; } stack.push(x); } public void pop() { int temp = stack.pop(); if(temp == min){ min = stack.pop(); } } public int top() { int temp = stack.peek(); return temp; } public int getMin() { return min; }
public class MinQueue { public static void main(String[] args){ MinQueue minQueue = new MinQueue(); minQueue.offer(0); minQueue.offer(-1); minQueue.offer(2); System.out.println(minQueue.getMin()); minQueue.offer(-3); minQueue.poll(); System.out.println(minQueue.getMin()); } Queue<Integer> queue = new LinkedList<>(); Queue<Integer> helper = new LinkedList<>(); int min = Integer.MAX_VALUE; public void offer(int x){ if(queue.isEmpty()){ helper.offer(x); queue.offer(x); min = x; } else if(x <= min){ queue.offer(x); int size = queue.size(); helper.offer(x); for(int i = 0; i <= size - 2; i++){ helper.poll(); helper.offer(x); } min = x; } else{ queue.offer(x); helper.offer(x); } } public void poll(){ if(!queue.isEmpty()){ queue.poll(); helper.poll(); min = helper.peek(); } } public int getMin(){ if(!queue.isEmpty()){ return helper.peek(); } else{ return -1; } } }

Comments
Post a Comment