Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack object.void push(int val)pushes the elementvalonto the stack.void pop()removes the element on the top of the stack.int top()gets the top element of the stack.int getMin()retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Example 1:
Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2
Constraints:
-231 <= val <= 231 - 1- Methods
pop,topandgetMinoperations will always be called on non-empty stacks. - At most
3 * 104calls will be made topush,pop,top, andgetMin.
SOL:
參考李根逸博士的影片,使用一個mins array來記錄在每個data位置的極小值。
不能只記整個stack的最小值,因為pop之後可能會把最小值pop掉。
【C 語言的 LeetCode 30 天挑戰】第十天 (Min Stack)
typedef struct {
int *data;
int *mins;
int size;
} MinStack;
MinStack* minStackCreate() {
MinStack *s = malloc(sizeof(MinStack));
s->data = NULL;
s->mins = NULL;
s->size = 0;
return s;
}
void minStackPush(MinStack* obj, int val) {
obj->data = realloc(obj->data, (sizeof(int)*(obj->size+1)));
obj->mins = realloc(obj->mins, (sizeof(int)*(obj->size+1)));
obj->data[obj->size]=val;
if((obj->size==0) || (obj->mins[obj->size-1]>val))
obj->mins[obj->size]=val;
else
obj->mins[obj->size]=obj->mins[obj->size-1];
obj->size++;
}
void minStackPop(MinStack* obj) {
obj->size--;
}
int minStackTop(MinStack* obj) {
return obj->data[obj->size-1];
}
int minStackGetMin(MinStack* obj) {
return obj->mins[obj->size-1];
}
void minStackFree(MinStack* obj) {
free(obj->data);
free(obj->mins);
free(obj);
}
/**
* Your MinStack struct will be instantiated and called as such:
* MinStack* obj = minStackCreate();
* minStackPush(obj, val);
* minStackPop(obj);
* int param_3 = minStackTop(obj);
* int param_4 = minStackGetMin(obj);
* minStackFree(obj);
*/
此外,影片中也有大致講一下 '.' 跟 '->'的用法差異,這個問題也困擾我好久,剛好老師一併講了。
Struct 用 '.' ;Struct pointer 用 '->'
(*fooPtr).yy 等價於 fooPtr->yy:'->' 可以用 '*' 跟 '.'來表示,不過有點噁心,所以才用 '->' 這個語法糖。
文章標籤
全站熱搜
