[Swift Weekly Contest 118]LeetCode969.煎餅排序 | Pancake Sorting
阿新 • • 發佈:2019-01-06
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,2,4,3]
Explanation:
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: A = [3, 2, 4, 1]
After 1st flip (k=4): A = [1, 4, 2, 3]
After 2nd flip (k=2): A = [4, 1, 2, 3]
After 3rd flip (k=4): A = [3, 2, 1, 4]
After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted.
Example 2:
Input: [1,2,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:
1 <= A.length <= 100
A[i]
is a permutation of[1, 2, ..., A.length]
給定陣列 A
k <= A.length
,然後反轉 A
的前 k 個元素的順序。我們要執行零次或多次煎餅翻轉(按順序一次接一次地進行)以完成對陣列 A
的排序。
返回能使 A
排序的煎餅翻轉操作所對應的 k 值序列。任何將陣列排序且翻轉次數在 10 * A.length
範圍內的有效答案都將被判斷為正確。
示例 1:
輸入:[3,2,4,1] 輸出:[4,2,4,3] 解釋: 我們執行 4 次煎餅翻轉,k 值分別為 4,2,4,和 3。 初始狀態 A = [3, 2, 4, 1] 第一次翻轉後 (k=4): A = [1, 4, 2, 3] 第二次翻轉後 (k=2): A = [4, 1, 2, 3] 第三次翻轉後 (k=4): A = [3, 2, 1, 4] 第四次翻轉後 (k=3): A = [1, 2, 3, 4],此時已完成排序。
示例 2:
輸入:[1,2,3] 輸出:[] 解釋: 輸入已經排序,因此不需要翻轉任何內容。 請注意,其他可能的答案,如[3,3],也將被接受。
提示:
1 <= A.length <= 100
A[i]
是[1, 2, ..., A.length]
的排列
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 }