11 Nisan 2020 Cumartesi

Basit Stack Veri Yapısı


Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/529/week-2/3292/
 

>> Solution 1 :Basit linked list, her node'da minimumu tut

/**
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
* Your MinStack object will be instantiated and called as such:
*
* > MinStack obj = new MinStack();
* > obj.push(x);
* > obj.pop();
* > int param_3 = obj.top();
* > int param_4 = obj.getMin();
*
*/
class MinStack {
private Node top;
public MinStack() {
top = null;
}
public void push(int element) {
top = new Node (element, top);
}
public void pop() {
Node popped = top;
top = top.next;
}
public int top() {
return top.value;
}
public int getMin() {
return top.minValue;
}
private class Node {
int value;
int minValue;
Node next;
Node(int value,Node next){
this.value = value;
this.next = next;
if(next == null || value < next.minValue){
minValue = value;
} else {
minValue = next.minValue;
}
}
}
}
view raw MinStack.java hosted with ❤ by GitHub
O(1) time complexity, O(n) space complexity

Hiç yorum yok: