Summary of Lituo solution 1053. Exchange the previous permutation once

Directory link:

Lituo Programming Problems - Summary of Solutions_Share+Records-CSDN Blog

GitHub synchronous brushing project:

https://github.com/September26/java-algorithms

Original title link:

Leek


describe:

Given an array of positive integers  arr(there may be duplicate elements), please return the   largest permutation that can  be obtained after  one exchange (exchanging the positions of the sum of two numbers  arr[i] )  in lexicographical order less than.arr[j]arr

If this is not possible, please return the original array.

Example 1:

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

Example 2:

Input: arr = [1,1,5]
 Output: [1,1,5]
 Explanation: Already the smallest permutation

Example 3:

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

hint:

  • 1 <= arr.length <= 104
  • 1 <= arr[i] <= 104

Problem-solving ideas:

* Problem-solving ideas:
* Use the strategy of priority solution.
* First of all, the later the replacement position, the smaller the lexicographical change. So find the first number whose arr[i] is smaller than arr[i+1] and replace it.
* Secondly, the two exchanged positions index and maxIndex, the larger the value of arr[maxIndex], the smaller the lexicographical change, so after finding the index, it is smaller than the maximum value of arr[index].
* Finally, if there are multiple such values, the one with the highest position is taken. Because arr[index]>arr[maxIndex], the closer the position of maxIndex is, the larger the value after exchange.

code:

public class Solution1053 {

    public int[] prevPermOpt1(int[] arr) {
        int index = arr.length - 2;
        for (int i = arr.length - 2; i >= 0; i--) {
            if (arr[i] > arr[i + 1]) {
                index = i;
                break;
            }
        }
        int maxIndex = 0;
        int max = 0;
        for (int i = arr.length - 1; i > index; i--) {
            int value = arr[i];
            if (value >= arr[index]) {
                continue;
            }
            if (value >= max) {
                maxIndex = i;
                max = value;
            }
        }
        int local = arr[index];
        arr[index] = arr[maxIndex];
        arr[maxIndex] = local;
        return arr;
    }
}

Guess you like

Origin blog.csdn.net/AA5279AA/article/details/129926258