双栈排序
来源:互联网 发布:linux ftp put命令 编辑:程序博客网 时间:2024/06/14 06:52
题目描述
请编写一个程序,按升序对栈进行排序(即最大元素位于栈顶),要求最多只能使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。
给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,请返回排序后的栈。请注意这是一个栈,意味着排序过程中你只能访问到第一个元素。
测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]
import java.util.*;public class TwoStacks { public ArrayList<Integer> twoStacksSort(int[] numbers) { // write code here ArrayList<Integer> res = new ArrayList<Integer>(); if(numbers.length==0) return res; Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); for(int i=0; i<numbers.length; ++i){ if(stack1.isEmpty()){ stack1.push(numbers[i]); continue; } while(!stack1.isEmpty()&&stack1.peek() > numbers[i]){ stack2.push(stack1.pop()); } stack1.push(numbers[i]); while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } } while(!stack1.isEmpty()){ res.add(stack1.pop()); } return res; }}
0 0
- [NOIP2008]双栈排序
- NOIP2008 双栈排序
- sicily双栈排序
- 双栈排序
- [noip2008]双栈排序
- 双栈排序
- Codevs1170 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- 双栈排序
- P1155 双栈排序
- 1002. 双栈排序
- 双栈排序
- 双栈排序
- 硬件描述语言相关
- MyISAM与InnoDB区别
- 快学scala第十六章习题——XML处理
- shared_ptr
- WebService学习总结(三)——使用JDK开发WebService
- 双栈排序
- JAVA线程学习笔记
- HBbase的部署与实施
- 棋盘覆盖问题
- win7上Mysql导出(多张表)表结构及表数据 mysqldump用法
- Swift 数组中 Map,FlatMap,Filter,Reduce的使用
- 【Android】12、更多隐式Intent的用法
- FZU 2227 邮票 (DFS+ 离散化 水题)
- Mafile补充学习1~2