原题说明
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.
Example 1:
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:
Input: [3,1,1,3]
Output: [1,3,1,3]
Explanation: Swapping 1 and 3.
Note:
1 <= A.length <= 100001 <= A[i] <= 10000
解题思路
我们找到A当中需要交换的位置left和right:
left的位置应当尽量往右:应当为A从右往左第一个变大的位置,因为其右边肯定有比其小的值了。
找到left的位置后,right应当是left右侧最大的数:
由于left右侧为从右往左递减的序列(从左往右递增),所以需要从右往左找到第一个大于A[left]的数A[right]。
如果A[right]有连续相同的数,比如[3, 1, 1, 3]中中间连续的1,那么我们希望right指向最左侧的那个1。
所以我们还需要继续将right向左移直到A[right] != A[right - 1]。
此时交换A[right]与A[left],并返回A即可。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | public class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(N)
空间复杂度: O(1)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!