1053. Previous Permutation With One Swap

Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap (A swap exchanges the positions of two numbers arr[i] and arr[j]). If it cannot be done, then return the same array.

 

Example 1:

Input: arr = [3,2,1]
Output: [3,1,2]
Explanation: Swapping 2 and 1.

Example 2:

Input: arr = [1,1,5]
Output: [1,1,5]
Explanation: This is already the smallest permutation.

Example 3:

Input: arr = [1,9,4,6,7]
Output: [1,7,4,6,9]
Explanation: Swapping 9 and 7.

Example 4:

Input: arr = [3,1,1,3]
Output: [1,3,1,3]
Explanation: Swapping 1 and 3.

 1 class Solution {
 2     public int[] prevPermOpt1(int[] A) {
 3         if (A.length <= 1) return A;
 4         int idx = -1;
 5         // find the largest i such that A[i] > A[i + 1] (a local max)
 6         for (int i = A.length - 1; i >= 1; i--) {
 7             if (A[i] < A[i - 1]) {
 8                 idx = i - 1;
 9                 break;
10             }
11         }
12         // the array already sorted, not smaller permutation
13         if (idx == -1) return A;
14         // find the largest j such that A[j] > A[i], then swap them
15         for (int i = A.length - 1; i > idx; i--) {
16             // the second check to skip duplicate numbers // [3,1,1,3] => [1,3,1,3] If we ignore the second check, it becomes [1,1,3,3]
17             if (A[i] < A[idx] && A[i] != A[i - 1]) {
18                 int tmp = A[i];
19                 A[i] = A[idx];
20                 A[idx] = tmp;
21                 break;
22             }
23         }
24         return A;
25     }
26 }

ref: https://leetcode.com/problems/previous-permutation-with-one-swap/discuss/299244/Similar-to-find-previous-permutation-written-in-Java

posted @ 2020-12-27 01:47  北叶青藤  阅读(127)  评论(0)    收藏  举报