Solution:
1) LinkedList
Node head;
public MinStack() {
// do intialization if necessary
head = null;
}
/*
* @param number: An integer
* @return: nothing
*/
public void push(int number) {
// write your code here
if (head == null) {
head = new Node(number, number, null);
} else {
head = new Node(number, Math.min(number, head.min), head);
}
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
int rst = head.val;
head = head.next;
return rst;
}
/*
* @return: An integer
*/
public int min() {
// write your code here
return head.min;
}
private class Node {
int val;
int min;
Node next;
public Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
2) Two stack
Deque<Integer> s1;
Deque<Integer> s2;
public MinStack() {
s1 = new ArrayDeque<Integer>();
s2 = new ArrayDeque<Integer>();
}
public void push(int number) {
s1.push(number);
if (s2.isEmpty() || number <= min()) s2.push(number);
}
public int pop() {
if (s1.peek() == min()) s2.pop();
return s1.pop();
}
public int min() {
return s2.peek();
}
Tuesday, March 27, 2018
Subscribe to:
Post Comments (Atom)
4. Ugly Number
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
-
Given a list, rotate the list to the right by k places, where k is non-negative. Wrong solution 1: public ListNode rotateRight(ListNo...
-
if (head == null || head . next == null ) { return head; } ListNode lessDummy = new ListNode (...
-
1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...
No comments:
Post a Comment