1. 程式人生 > >劍指offer刷題記錄20——包含min函式的棧

劍指offer刷題記錄20——包含min函式的棧

題目描述

定義棧的資料結構,請在該型別中實現一個能夠得到棧中所含最小元素的min函式(時間複雜度應為O(1))。

解法:

import java.util.Stack;
import java.util.Iterator;

public class Solution {

    Stack<Integer> stack = new Stack<Integer>();
    public void push(int node) {
        stack.push(node);
    }
    
    public void pop() {
        stack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        int min = Integer.MAX_VALUE;
        Iterator<Integer> it = stack.iterator();
        while(it.hasNext()) {
            min = Math.min(it.next(), min);
        }
        return min;
    }
}

方法總結:

stack.push(int node) 將node壓入棧中

stack.pop()      移除並返回棧頂物件

stack.peek() (不移除)並返回棧頂物件

iterator.hasNext() 判斷序列中是否還有元素

iterator.next()  返回序列的下一個元素

當首次建立某個容器的迭代器時,其指標指向的是該容器第一個元素上方的空白