Advertisement
Guest User

969. Pancake Sorting

a guest
Feb 17th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. // Time: O(n2), Space: O(n)
  2. class Solution {
  3.    
  4.     // https://leetcode.com/problems/pancake-sorting/discuss/214213/JavaC%2B%2BPython-Straight-Forward
  5.     public List<Integer> pancakeSort(int[] A) {
  6.         List<Integer> result = new ArrayList<>();
  7.         if (A == null || A.length <= 1) {
  8.             return result;
  9.         }
  10.        
  11.         for (int x=A.length; x>=1; x--) {
  12.             int i=0;
  13.             while (A[i] != x) {
  14.                 i++;
  15.             }
  16.             if (i+1 == x) {
  17.                 continue;
  18.             }
  19.             reverse(A, i+1);
  20.             reverse(A, x);
  21.             result.add(i+1);
  22.             result.add(x);
  23.         }
  24.        
  25.         return result;
  26.     }
  27.    
  28.     public void reverse(int[] A, int k) {
  29.         int i = 0;
  30.         int j = k-1;
  31.         while (i < j) {
  32.             int tmp = A[i];
  33.             A[i] = A[j];
  34.             A[j] = tmp;
  35.             i++;
  36.             j--;
  37.         }
  38.     }
  39.    
  40.     // See solution for mor details
  41.     public List<Integer> pancakeSortMethod2(int[] A) {
  42.         List<Integer> result = new ArrayList<>();
  43.         if (A == null || A.length <= 1) {
  44.             return result;
  45.         }
  46.        
  47.         int n = A.length;
  48.         Integer[] B = new Integer[n];
  49.         for (int i=0; i<n; i++) {
  50.             B[i] = i+1;
  51.         }
  52.         Arrays.sort(B, (a, b) -> (A[b-1] - A[a-1]));
  53.        
  54.         for (int b : B) {
  55.             for (int ps : result) {
  56.                 if (b <= ps) {
  57.                     b = 1 + (ps-b);
  58.                 }
  59.             }
  60.            
  61.             if (b < n) {
  62.                 result.add(b);
  63.                 result.add(n);
  64.             }
  65.            
  66.             n--;
  67.         }
  68.        
  69.         return result;
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement