zoukankan      html  css  js  c++  java
  • [CTCI] 双栈排序

    双栈排序

    题目描述

    请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。

    给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。

    测试样例:
    [1,2,3,4,5]
    返回:[5,4,3,2,1]


     1 class TwoStacks {
     2 public:
     3     vector<int> twoStacksSort(vector<int> numbers) {
     4         // write code here
     5         stack<int> stk;
     6         int top = 0, tmp;
     7         while (top != numbers.size()) {
     8             tmp = numbers[top++];
     9             while (!stk.empty() && stk.top() > tmp) {
    10                 numbers[--top] = stk.top();
    11                 stk.pop();
    12             }
    13             stk.push(tmp);
    14         }
    15         top = 0;
    16         while (!stk.empty()) {
    17             numbers[top++] = stk.top();
    18             stk.pop();
    19         }
    20         return numbers;
    21     }
    22 };
  • 相关阅读:
    ORM是什么?
    mysql 杂谈
    IO model之IO多路复用的触发方式
    IO model之select poll epoll IO多路复用介绍
    IO model
    事件驱动模型介绍
    函数
    商品程序
    随机生成密码
    import radom 和import string
  • 原文地址:https://www.cnblogs.com/easonliu/p/4656772.html
Copyright © 2011-2022 走看看