每日一题 2019 - 01 - 24
题目:
Given an array A
, we can perform a pancake flip: We choose some positive integer **k** <= A.length
, then reverse the order of the first k elements of A
. We want to perform zero or more pancake flips (doing them one after another in succession) to sort the array A
.
Return the k-values corresponding to a sequence of pancake flips that sort A
. Any valid answer that sorts the array within 10 * A.length
flips will be judged as correct.
Example 1:
1 | Input: [3,2,4,1] |
Example 2:
1 | Input: [1,2,3] |
Note:
1 <= A.length <= 100
A[i]
is a permutation of[1, 2, ..., A.length]
解法:
这个题的意思是让我们使用pancake sort
对给定数组进行排序,并且记录下每次排序的位置,关于pancake sort
的排序思路是:
- 每次找出最大的待排元素的位置
pos
- 翻转 0 到 pos 位置的元素
- 记录 pos + 1
- 翻转 0 到 末尾(这里的末尾指的是待排序列的末尾,每两次翻转之后,都会有一个元素被放置在应该放置的位置)
- 记录 末尾元素 i
返回上述的记录过程
注:
这里有个地方需要提醒一下,题目中给出的example
的序列[3,2,4,1]
的正确排序过程应该是[3,4,2,3,1,2]
代码:
1 | class Solution { |