劍指offer(二十)包含min函數(shù)的棧

點(diǎn)擊進(jìn)入 ??途W(wǎng)題庫(kù):包含min函數(shù)的棧

題目描述

定義棧的數(shù)據(jù)結(jié)構(gòu),請(qǐng)?jiān)谠擃愋椭袑?shí)現(xiàn)一個(gè)能夠得到棧中所含最小元素的min函數(shù)(時(shí)間復(fù)雜度應(yīng)為O(1))。
注意:保證測(cè)試中不會(huì)當(dāng)棧為空的時(shí)候,對(duì)棧調(diào)用pop()或者min()或者top()方法。

方法一 解法不滿足題目要求,不過(guò)獲取正確數(shù)據(jù)

import java.util.Stack;

/**
* 我這個(gè)時(shí)間復(fù)雜度有問(wèn)題,有個(gè)o(n)在里頭,就是
* 那個(gè)findMin是個(gè)o(n)的復(fù)雜度
*
*/
public class Solution {
    private Stack<Integer> stack;
    private int min;
    
    public Solution() {
        stack = new Stack<Integer>();
    }
    
    public void push(int node) {
        stack.push(node);
        if(stack.size() == 1) {
            min = node;
        } else {
           findMin();
        }
        
    }
    private void findMin() {
        //如果值小于等于的時(shí)候,每次要找出其中的最小值
        min = stack.get(0);
        for(int i = 1; i < stack.size(); i++) {
               min = Math.min(stack.get(i), min);
        }
    }
    
    public void pop() {
         int popValue = stack.pop();
        if(stack.size() == 1) {
            min = stack.get(0);
        } else {
           if(popValue <= min) {
                 findMin();
           } else {
               //值不受影響
           }
        }
    }
    
    public int top() {
        int popValue = stack.pop();
        if(stack.size() == 1) {
            min = stack.get(0);
        } else {
           
           if(popValue <= min) {
                 findMin();
           } else {
               //值不受影響
           }
        }
        return popValue;
    }
    
    public int min() {
        return min;
    }
}

方法二 (借用第二個(gè)棧,輔助空間解決)

import java.util.Stack;

public class Solution {
    private Stack<Integer> stack;
    private Stack<Integer> stack2;
    private int min;
    
    public Solution() {
        stack = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }
    
    public void push(int node) {
        stack.push(node);
        
        if(stack2.isEmpty()) {
            stack2.push(node);
        } else {
            if(stack2.peek() >= node) {
                stack2.push(node);
            }
        }
    }

    public void pop() {
        
         int popValue = stack.pop();
         if(popValue == stack2.peek()) {
             stack2.pop();
         }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return stack2.peek();
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容