码迷,mamicode.com
首页 > 其他好文 > 详细

Sort With 3 Stacks - Medium

时间:2019-01-03 19:42:10      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:span   top   lob   color   pre   global   origin   solution   original   

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

Sort With 3 Stacks - Medium

标签:span   top   lob   color   pre   global   origin   solution   original   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!