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

Sort With 2 Stacks - Medium

时间:2019-01-04 14:33:09      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:ISE   oid   return   mem   bsp   重复   nbsp   style   sorted   

Given an array that is initially stored in one stack, sort it with one additional stacks (total 2 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(n ^ 2).

 

基于selection sort,一个stack即当buffer又当output,每次倒的时候记录global min及出现次数(以防重复元素)

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

public class Solution {
  public void sort(LinkedList<Integer> s1) {
    LinkedList<Integer> s2 = new LinkedList<Integer>();
    // Write your solution here.
    if(s1 == null || s1.size() < 0) {
      return;
    }
    int cnt = 0;
    while(!s1.isEmpty()) {
      int globalMin = Integer.MAX_VALUE;
      while(!s1.isEmpty()) {
        int tmp = s1.pop();
        if(tmp < globalMin) {
          globalMin = tmp;
        }
        s2.push(tmp);
      }
      while(!s2.isEmpty() && s2.peek() >= globalMin) {
        int tmp = s2.pop();
        if(tmp == globalMin) {
          cnt++;
        } else {
          s1.push(tmp);
        }
      }
      while(cnt > 0) {
        s2.push(globalMin);
        cnt--;
      }
    }
    
    while(!s2.isEmpty()) {
      s1.push(s2.pop());
    }
  }
}

 

Sort With 2 Stacks - Medium

标签:ISE   oid   return   mem   bsp   重复   nbsp   style   sorted   

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

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