LeetCode 969. Pancake Sorting
考点 | 难度 |
---|---|
Greedy | Easy |
题目
Given an array of integers arr, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:
Choose an integer k where 1 <= k <= arr.length.
Reverse the sub-array arr[0…k-1] (0-indexed).
For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.
Return an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.
思路
找到最大的数x(假设在index n)先flip前n个数让最大的数到第一位,再flip x个数(因为是从1开始的连续整数)让它到最后一位
答案
class Solution:
def pancakeSort(self, A):
result, n = [], len(A)
for i in range(n,0,-1):
pl = A.index(i)
if pl == i-1: continue
if pl != 0:
result.append(pl+1)
A[:pl+1] = A[:pl+1][::-1]
result.append(i)
A[:i] = A[:i][::-1]
return result