★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-vseuwnka-mc.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an array A
of positive integers (not necessarily distinct), return the lexicographically largest permutation that is smaller than A
, that can be made with one swap (A swap exchanges the positions of two numbers A[i]
and A[j]
). If it cannot be done, then return the same array.git
Example 1:github
Input: [3,2,1] Output: [3,1,2] Explanation: Swapping 2 and 1.
Example 2:數組
Input: [1,1,5] Output: [1,1,5] Explanation: This is already the smallest permutation.
Example 3:微信
Input: [1,9,4,6,7] Output: [1,7,4,6,9] Explanation: Swapping 9 and 7.
Example 4:app
Input: [3,1,1,3] Output: [1,1,3,3]
Note:ide
1 <= A.length <= 10000
1 <= A[i] <= 10000
給你一個正整數的數組 A
(其中的元素不必定徹底不一樣),請你返回可在 一次交換(交換兩數字 A[i]
和 A[j]
的位置)後獲得的、按字典序排列小於 A
的最大可能排列。spa
若是沒法這麼操做,就請返回原數組。code
示例 1:htm
輸入:[3,2,1] 輸出:[3,1,2] 解釋: 交換 2 和 1
示例 2:
輸入:[1,1,5] 輸出:[1,1,5] 解釋: 這已是最小排列
示例 3:
輸入:[1,9,4,6,7] 輸出:[1,7,4,6,9] 解釋: 交換 9 和 7
示例 4:
輸入:[3,1,1,3] 輸出:[1,1,3,3]
提示:
1 <= A.length <= 10000
1 <= A[i] <= 10000
1 class Solution { 2 func prevPermOpt1(_ A: [Int]) -> [Int] { 3 var A = A 4 let n:Int = A.count 5 for i in stride(from:n - 1,to:0,by:-1) 6 { 7 if A[i-1] <= A[i] {continue} 8 let id:Int = i - 1 9 for j in stride(from:n - 1,to:id,by:-1) 10 { 11 if A[id] <= A[j] {continue} 12 A.swapAt(id,j) 13 return A 14 } 15 } 16 return A 17 } 18 }
1 class Solution { 2 func prevPermOpt1(_ A: [Int]) -> [Int] { 3 var A = A, i = A.count - 2 4 while i >= 0 && A[i] <= A[i+1] { 5 i -= 1 6 } 7 8 guard i >= 0 else { return A } 9 10 var lo = i + 1, hi = A.count 11 while lo < hi { 12 let mid = lo + (hi - lo) / 2 13 if A[i] > A[mid] { 14 lo = mid + 1 15 } else { 16 hi = mid 17 } 18 } 19 20 var target = lo - 1 21 while target > i && A[target] == A[target-1] { 22 target -= 1 23 } 24 A.swapAt(i, target) 25 return A 26 } 27 }
276ms
1 class Solution { 2 func prevPermOpt1(_ A: [Int]) -> [Int] { 3 var A = A, i = A.count - 2 4 while i >= 0 && A[i] <= A[i+1] { 5 i -= 1 6 } 7 8 guard i >= 0 else { return A } 9 10 var lo = i + 1, hi = A.count 11 while lo < hi { 12 let mid = lo + (hi - lo) / 2 13 if A[i] > A[mid] { 14 lo = mid + 1 15 } else { 16 hi = mid 17 } 18 } 19 20 A.swapAt(i, lo - 1) 21 return A 22 } 23 }