美文网首页北美程序员面试干货
LintCode 229 [Stack Sorting]

LintCode 229 [Stack Sorting]

作者: Jason_Yuan | 来源:发表于2016-07-07 15:49 被阅读75次

原题

请设计一种方法将一个栈进行升序排列 (最大的数在最上面)。

你可以使用另外一个栈来辅助操作,但不可将这些数复制到另外一个数据结构中 (如,数组)。

样例
给一个栈:

| |
|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)

相关文章

  • LintCode 229 [Stack Sorting]

    原题 请设计一种方法将一个栈进行升序排列 (最大的数在最上面)。 你可以使用另外一个栈来辅助操作,但不可将这些数复...

  • LintCode 495 [Implement Stack]

    原题 实现一个栈,可以使用除了栈之外的数据结构 样例 解题思路 使用python list实现stack数据结构 ...

  • Basic Algorithm

    Sorting Algorithm Setup and Driver Program Each sorting a...

  • Harry Potter and The Sorcerer's

    Chapter 7 The Sorting Hat Sorting was a very important ce...

  • Lintcode12 Min Stack solution 题解

    【题目描述】 Implement a stack with min() function, which will ...

  • Comparable vs Comparator

    sorting 排序 sorting-in-javaJava中提供了Arrays.sort()和Collectio...

  • Sorting

    本文是我正在写的gitbook上的书Algorithms一个章节,由于是记录课程的内容,所以下文都是英文,见谅。 ...

  • Sorting

    排序与相关性 1、排序默认是根据相关性_score进行降序排序。filter会导致_score为0,如果0分对我们...

  • Sorting

    排序是算法里面一个老生常态的内容,基本是所有算法的第一关。 插入排序 算法思路 最简单的排序莫过于插入排序,需要N...

  • 拓扑排序(Topological Sorting)

    拓扑排序(Topological Sorting)拓扑排序(Topological Sorting)是一个有向无环...

网友评论

    本文标题:LintCode 229 [Stack Sorting]

    本文链接:https://www.haomeiwen.com/subject/kdlljttx.html