---
# System prepended metadata

title: \#155 Min Stack
tags: [leetcode, leetcode-easy]

---

# \#155 Min Stack
## *實作資料結構(數字陣列)與方法, 使方法得以回傳該陣列的初始化結構/push()/pop()/top()/getMin()(取得陣列中最小元素)*
## Log
 - build 20210405 by syhuang

## 初見
 - javascript已有提供陣列的大多數方法可用, 這題主要實作在物件的初始化(this運用)和取最小元素
```javascript=
/**
 * initialize your data structure here.
 */
var MinStack = function() {
    this.elements = [];
};

/** 
 * @param {number} val
 * @return {void}
 */
MinStack.prototype.push = function(val) {
    this.elements.push(val);
};

/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
    this.elements.pop();
};

/**
 * @return {number}
 */
MinStack.prototype.top = function() {
    return this.elements[this.elements.length-1];
};

/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    var result = this.elements[0];
    for(var i=1; i<this.elements.length; i++){
        result = Math.min(result,this.elements[i]);
    }
    return result;
};
```
## 備註
 - getMin()還可以再改良, 物件多紀錄一個min屬性, 在push()和pop()方法同時更新min值, 讓getMin()時間複雜度下降
## 參考
###### tags: `leetcode`, `leetcode-easy`