LeetCode 1053. Previous Permutation With One Swap

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 1053. Previous Permutation With One Swap相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/previous-permutation-with-one-swap/

题目:

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. 1 <= A.length <= 10000
  2. 1 <= A[i] <= 10000

题解:

From right to left, find the first element A[i - 1] > A[i]. Mark first position = i - 1.

If we can\'t find it, then there is no previouis perrmutation.

Then mark second position = i, and for j > i, find the last position that A[j] > A[j - 1] && A[j] < A[first]. If we find any, keep updating second position.

Swap first and second positions.

Time Complexity: O(n). n = A.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int[] prevPermOpt1(int[] A) {
 3         if(A == null || A.length == 0){
 4             return A;
 5         }
 6         
 7         int n = A.length;
 8         int i = n - 1;
 9         while(i >= 1 && A[i] >= A[i - 1]){
10             i--;
11         }
12         
13         if(i == 0){
14             return A;
15         }
16         
17         int first = i - 1;
18         int second = i;
19         for(int j = i + 1; j < n; j++){
20             if(A[j] > A[j - 1] && A[j] < A[first]){
21                 second = j;
22             }
23         }
24             
25         int temp = A[first];
26         A[first] = A[second];
27         A[second] = temp;
28         return A;
29     }
30 }

类似Next Permutation.

以上是关于LeetCode 1053. Previous Permutation With One Swap的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 1053. Previous Permutation With One Swap

leetcode1053

数组旋转 Leetcode#189

[BZOJ1053][SDOI2005]反素数ant 数学

bzoj1053&&51nod1060

P1053 篝火晚会