程序员面试题精选100题(02)-设计包含min函数的栈[数据结构]
分析:這是去年google的一道面試題。
我看到這道題目時,第一反應就是每次push一個新元素時,將棧里所有逆序元素排序。這樣棧頂元素將是最小元素。但由于不能保證最后push進棧的元素最先出棧,這種思路設計的數據結構已經不是一個棧了。
在棧里添加一個成員變量存放最小元素(或最小元素的位置)。每次push一個新元素進棧的時候,如果該元素比當前的最小元素還要小,則更新最小元素。
乍一看這樣思路挺好的。但仔細一想,該思路存在一個重要的問題:如果當前最小元素被pop出去,如何才能得到下一個最小元素?
因此僅僅只添加一個成員變量存放最小元素(或最小元素的位置)是不夠的。我們需要一個輔助棧。每次push一個新元素的時候,同時將最小元素(或最小元素的位置。考慮到棧元素的類型可能是復雜的數據結構,用最小元素的位置將能減少空間消耗)push到輔助棧中;每次pop一個元素出棧的時候,同時pop輔助棧。
參考代碼:
#include <deque> #include <assert.h>template <typename T> class CStackWithMin { public:CStackWithMin(void) {}virtual ~CStackWithMin(void) {}T& top(void);const T& top(void) const;void push(const T& value);void pop(void);const T& min(void) const;private:T> m_data; // the elements of stacksize_t> m_minIndex; // the indices of minimum elements };// get the last element of mutable stack template <typename T> T& CStackWithMin<T>::top() {return m_data.back(); }// get the last element of non-mutable stack template <typename T> const T& CStackWithMin<T>::top() const {return m_data.back(); }// insert an elment at the end of stack template <typename T> void CStackWithMin<T>::push(const T& value) {// append the data into the end of m_datam_data.push_back(value);// set the index of minimum elment in m_data at the end of m_minIndexif(m_minIndex.size() == 0)m_minIndex.push_back(0);else{if(value < m_data[m_minIndex.back()])m_minIndex.push_back(m_data.size() - 1);elsem_minIndex.push_back(m_minIndex.back());} }// erease the element at the end of stack template <typename T> void CStackWithMin<T>::pop() {// pop m_datam_data.pop_back();// pop m_minIndexm_minIndex.pop_back(); }// get the minimum element of stack template <typename T> const T& CStackWithMin<T>::min() const {assert(m_data.size() > 0);assert(m_minIndex.size() > 0);return m_data[m_minIndex.back()]; }
舉個例子演示上述代碼的運行過程:
? 步驟????????????? 數據棧??????????? 輔助棧??????????????? 最小值
1.push 3??? 3????????? 0???????????? 3
2.push 4??? 3,4??????? 0,0?????????? 3
3.push 2??? 3,4,2????? 0,0,2???????? 2
4.push 1??? 3,4,2,1??? 0,0,2,3?????? 1
5.pop?????? 3,4,2????? 0,0,2???????? 2
6.pop?????? 3,4??????? 0,0?????????? 3
7.push 0??? 3,4,0????? 0,0,2???????? 0
討論:如果思路正確,編寫上述代碼不是一件很難的事情。但如果能注意一些細節無疑能在面試中加分。比如我在上面的代碼中做了如下的工作:
·???????? 用模板類實現。如果別人的元素類型只是int類型,模板將能給面試官帶來好印象;
·???????? 兩個版本的top函數。在很多類中,都需要提供const和非const版本的成員訪問函數;
·???????? min函數中assert。把代碼寫的盡量安全是每個軟件公司對程序員的要求;
·???????? 添加一些注釋。注釋既能提高代碼的可讀性,又能增加代碼量,何樂而不為?
總之,在面試時如果時間允許,盡量把代碼寫的漂亮一些。說不定代碼中的幾個小亮點就能讓自己輕松拿到心儀的Offer。
本文已經收錄到《劍指Offer——名企面試官精講典型編程題》一書中,有改動,書中的分析講解更加詳細。歡迎關注。我在英文博客上提供了一種不需要輔助棧的算法。感興趣的讀者請參考http://codercareer.blogspot.com/2011/09/no-02-stack-with-function-min.html。
博主何海濤對本博客文章享有版權。網絡轉載請注明出處http://zhedahht.blog.163.com/。整理出版物請和作者聯系。對解題思路有任何建議,歡迎在評論中告知,或者加我微博http://weibo.com/zhedahht或者http://t.163.com/zhedahht與我討論。謝謝。
總結
以上是生活随笔為你收集整理的程序员面试题精选100题(02)-设计包含min函数的栈[数据结构]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 程序员面试题精选100题(01)-把二元
- 下一篇: 程序员面试题精选100题(03)-子数组