1. 程式人生 > >Sort With 3 Stacks - Medium

Sort With 3 Stacks - Medium

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()