Stack Sorting

Question

Sort a stack in ascending order (with biggest terms on top).

You may use at most one additional stack to hold items, but you may not copy the elements into any other data structure (e.g. array).

Example

Given stack =

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

return:

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

The data will be serialized to [4,2,1,3]. The last element is the element on the top of the stack.

Challenge

O(n^2) time is acceptable.

Analysis

根据题目提示,可以设想利用另一个stack作为临时储存空间,设定的规则是:

  1. 从origin stack中不断pop() element
  2. 对于helper stack,如果helper stack peek() < element,则将helper stack中的元素全部转移到origin stack
  3. 再将element push()到helper stack中
  4. 不断重复上述步骤,直到origin stack isEmpty
  5. 最后,所有的元素已经按照descending order排序好(smallest on top),只需将其转移到origin stack,则origin stack即为所需排序

时间复杂度为O(n^2),空间复杂度为O(n)

Solution

public class Solution {
    /**
     * @param stack an integer stack
     * @return void
     */
    public void stackSorting(Stack<Integer> stack) {
        Stack<Integer> helpStack = new Stack<Integer>();
        while (!stack.isEmpty()) {
            int element = stack.pop();
            while (!helpStack.isEmpty() && helpStack.peek() < element) {
                stack.push(helpStack.pop());
            }
            helpStack.push(element);
        }
        while (!helpStack.isEmpty()) {
            stack.push(helpStack.pop());
        }
    }
}

Reference

results matching ""

    No results matching ""