zoukankan      html  css  js  c++  java
  • [Algo] 280. Sort With 2 Stacks

    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.
    • There can be duplicated numbers in the give stack.

    Requirements:

    • No additional memory, time complexity = O(n ^ 2).
    public class Solution {
      public void sort(LinkedList<Integer> s1) {
        LinkedList<Integer> s2 = new LinkedList<Integer>();
        // Write your solution here.
        while (!s1.isEmpty()) {
          s2.offerFirst(s1.pollFirst());
        }
    
        while (!s2.isEmpty()) {
          Integer cur = s2.pollFirst();
          while (!s1.isEmpty() && cur > s1.peekFirst()) {
            s2.offerFirst(s1.pollFirst());
          }
          s1.offerFirst(cur);
        }
      }
    }
  • 相关阅读:
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    lambda表达式
    VIM--保存和退出等命令
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12330313.html
Copyright © 2011-2022 走看看