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:
Input: [3,2,4,1]
Output: [4,3] Explanation: We perform 4 pancake flips,with k values 4,and 3. Starting state: A = [3,1] After 1st flip (k=4): A = [1,3] After 2nd flip (k=2): A = [4,1,3] After 3rd flip (k=4): A = [3,4] After 4th flip (k=3): A = [1,3,4],which is sorted.
Example 2:
Input: [1,3]
Output: [] Explanation: The input is already sorted,so there is no need to flip anything. Note that other answers,such as [3,3],would also be accepted.
Note:
给定数组 A
,我们可以对其进行煎饼翻转:我们选择一些正整数 k <= A.length
,然后反转 A
的前 k 个元素的顺序。我们要执行零次或多次煎饼翻转(按顺序一次接一次地进行)以完成对数组 A
的排序。
返回能使 A
排序的煎饼翻转操作所对应的 k 值序列。任何将数组排序且翻转次数在 10 * A.length
范围内的有效答案都将被判断为正确。
示例 1:
输入:[3,1] 输出:[4,3] 解释: 我们执行 4 次煎饼翻转,k 值分别为 4,2,4,和 3。 初始状态 A = [3,1] 第一次翻转后 (k=4): A = [1,3] 第二次翻转后 (k=2): A = [4,3] 第三次翻转后 (k=4): A = [3,4] 第四次翻转后 (k=3): A = [1,4],此时已完成排序。
示例 2:
输入:[1,3] 输出:[] 解释: 输入已经排序,因此不需要翻转任何内容。 请注意,其他可能的答案,如[3,3],也将被接受。
提示:
40ms
1 class Solution { 2 func pancakeSort(_ A: [Int]) -> [Int] { 3 var A = A 4 var n:Int = A.count 5 var ans:[Int] = [Int]() 6 for i in (0...(n - 1)).reversed() 7 { 8 var j:Int = 0 9 while(A[j] != i+1) 10 { 11 j += 1 12 } 13 ans.append(j + 1) 14 ans.append(i + 1) 15 var newA:[Int] = [Int](repeating:0,count:n) 16 for k in 0..<n 17 { 18 newA[k] = A[k] 19 } 20 for k in 0...j 21 { 22 newA[k] = A[j-k] 23 } 24 A = newA 25 newA = [Int](repeating:0,count:n) 26 for k in 0..<n 27 { 28 newA[k] = A[k] 29 } 30 for k in 0...i 31 { 32 newA[k] = A[i-k] 33 } 34 A = newA 35 } 36 return ans 37 } 38 }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。