给定一个int[] numbers(C++中为vector<int>),其中第一个元素为栈顶,请编写程序将栈进行升序排列(即最大元素位于栈顶),返回排序后的栈。要求最多使用一个额外的栈存放临时数据,但不得将元素复制到别的数据结构中。并注意这是一个栈,意味着排序过程中只能访问到最后一个元素。
测试样例:
[1,2,3,4,5]
返回:[5,4,3,2,1]
# -*- coding:utf-8 -*- class TwoStacks: def twoStacksSort(self, numbers): # write code here #辅助栈nums nums=[numbers.pop()] #遍历numbers栈顶 while numbers: #若nums为空(因为下面有逆序压入numbers的操作),将numbers栈顶压入nums(因为下面已经逆序压入了) if not nums: nums.append(numbers.pop()) else: a=numbers.pop() b=nums.pop() #如果numbers栈顶小于nums栈顶,将其压入nums if a<=b: nums.append(b) nums.append(a) #栈顶小的话,将其逆序压入numbers else: numbers.append(b) numbers.append(a) return nums
# -*- coding:utf-8 -*- class TwoStacks: def twoStacksSort(self, numbers): # write code here fuzhu = [] while numbers: count = 0 minnum = float('inf') while numbers: x = numbers.pop(0) count += 1 if x < minnum: minnum = x fuzhu.insert(0,x) count1 = 0 sign = 1 while count1 != count: y = fuzhu.pop(0) count1 += 1 if y == minnum and sign: sign = 0 continue else: numbers.insert(0,y) fuzhu.insert(0,minnum) return fuzhu
# -*- coding:utf-8 -*-
class TwoStacks:
def twoStacksSort(self, numbers):
if not numbers:
return []
result = []
while numbers:
tmp = numbers.pop()
while result and result[-1] < tmp:
numbers.append(result.pop())
result.append(tmp)
return result