LeetCode Solutions

969. Pancake Sorting

Time:

Space:

			

class Solution {
 public:
  vector<int> pancakeSort(vector<int>& A) {
    vector<int> ans;

    for (int target = A.size(); target >= 1; --target) {
      int index = find(A, target);
      reverse(begin(A), begin(A) + index + 1);
      reverse(begin(A), begin(A) + target);
      ans.push_back(index + 1);
      ans.push_back(target);
    }

    return ans;
  }

 private:
  int find(vector<int>& A, int target) {
    for (int i = 0; i < A.size(); ++i)
      if (A[i] == target)
        return i;
    throw;
  }
};
			

class Solution {
  public List<Integer> pancakeSort(int[] A) {
    List<Integer> ans = new ArrayList<>();

    for (int target = A.length; target >= 1; --target) {
      int index = find(A, target);
      reverse(A, 0, index);
      reverse(A, 0, target - 1);
      ans.add(index + 1);
      ans.add(target);
    }

    return ans;
  }

  private int find(int[] A, int target) {
    for (int i = 0; i < A.length; ++i)
      if (A[i] == target)
        return i;
    throw new IllegalArgumentException();
  }

  private void reverse(int[] A, int l, int r) {
    while (l < r)
      swap(A, l++, r--);
  }

  private void swap(int[] A, int l, int r) {
    int temp = A[l];
    A[l] = A[r];
    A[r] = temp;
  }
}
			

class Solution:
  def pancakeSort(self, A: List[int]) -> List[int]:
    ans = []

    for target in range(len(A), 0, -1):
      index = A.index(target)
      A[:index + 1] = A[:index + 1][::-1]
      A[:target] = A[:target][::-1]
      ans.append(index + 1)
      ans.append(target)

    return ans