Sort With 3 Stacks

Given one stack with integers, sort it with two additional stacks (total 3 stacks). 

After sorting the original stack should contain the sorted integers and from top to bottom the integers are sorted in ascending order.

Assumptions:

  • The given stack is not null.

Requirements:

  • No additional memory, time complexity = O(nlog(n)).

M1: 普通作法,来回倒,s2作为buffer,s3作为output,最后再把s3中排完序的数字倒入s1

time: O(n^2), space: O(n)

public class Solution {
  public void sort(LinkedList<Integer> s1) {
    LinkedList<Integer> s2 = new LinkedList<Integer>();
    LinkedList<Integer> s3 = new LinkedList<Integer>();
    // Write your solution here.
    if(s1 == null) {
      return;
    }
    
    while(!s1.isEmpty() || !s2.isEmpty()) {
      int globalMin = Integer.MAX_VALUE;
      while(!s1.isEmpty()) {
        int tmp = s1.pop();
        globalMin = tmp < globalMin ? tmp : globalMin;
        s2.push(tmp);
      }
      while(!s2.isEmpty()) {
        int tmp = s2.pop();
        if(tmp != globalMin) {
          s1.push(tmp);
        } else {
          s3.push(globalMin);
        }
      }
    }
    
    while(!s3.isEmpty()) {
      s1.push(s3.pop());
    }
  }
}

M2: merge sort

time: O(nlogn), space: O()

原文地址:https://www.cnblogs.com/fatttcat/p/10216064.html