LintCode 229 [Stack Sorting]

原題

請設計一種方法將一個棧進行升序排列 (最大的數(shù)在最上面)。

你可以使用另外一個棧來輔助操作,但不可將這些數(shù)復制到另外一個數(shù)據結構中 (如,數(shù)組)。

樣例
給一個棧:

| |
|3|
|1|
|2|
|4|
 -

排序之后:

| |
|4|
|3|
|2|
|1|
 -

棧會被序列化為[4,2,1,3],也就是說最右邊是棧頂。

解題思路

  • 首先,把所有元素從原stack倒進臨時stack,然后每次從臨時stack拿出一個元素放入current中:
  • 若該current大于原stack中最上面的元素,則直接加入原stack
  • 若該current小于原stack中的元素,就把原stack中的元素放回臨時stack,直到原stack頂上的元素小于current或者原stack為空,則將current放入原stack
  • 從而,保證了原stack中的元素從底到上是按有小到大排序的

完整代碼

#Your can use Stack class in your solution.
#class Stack:
#  def __init__(self, stk=[])
#    # use stk to initialize the stack
#  def isEmpty(self)
#    # return true is stack is empty or false/
#  def push(self, item)
#    # push a element into stack and return nothing
#  def pop(self)
#    # pop a element from stack
#  def peek(self):
#    # return the top element if stack is not empty or nothing
#  def size(self):
#    # return the size of stack
class Solution:
    # @param {Stack} stk an integer Stack
    # @return {int} void
    def stackSorting(self, stk):
        # Write your code here
        tempStk = Stack()
        while not stk.isEmpty():
            tempStk.push(stk.pop())

        while not tempStk.isEmpty():
            current = tempStk.pop()
            while not stk.isEmpty() and stk.peek() > current:
                tempStk.push(stk.peek())
                stk.pop()
            stk.push(current)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,936評論 0 33
  • 1 序 2016年6月25日夜,帝都,天下著大雨,拖著行李箱和同學在校門口照了最后一張合照,搬離寢室打車去了提前租...
    RichardJieChen閱讀 5,397評論 0 12
  • 從三月份找實習到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時芥藍閱讀 42,901評論 11 349
  • Java8張圖 11、字符串不變性 12、equals()方法、hashCode()方法的區(qū)別 13、...
    Miley_MOJIE閱讀 3,918評論 0 11
  • 1、眼動、腦電實驗2、可用性測試用戶在一定場景下使用產品,發(fā)現(xiàn)用戶在使用過程中的偏好、需求、痛點、路徑、習慣等,為...
    jlnbda3488375閱讀 393評論 0 0

友情鏈接更多精彩內容