leetcode 670. 最大交换

Question6

There is a number k and you can swap two digits at most once. Please design a greedy algorithm to find the maximum value you can get.
Input: k = 39748
Output: 93748

解题思路

leetcode 670. 最大交换_第1张图片

代码实现

class Solution {
    public int maximumSwap(int num) {
        char[] charArray = String.valueOf(num).toCharArray();
        int n = charArray.length;
        int maxIdx = n - 1;
        int idx1 = -1, idx2 = -1;
        for (int i = n - 1; i >= 0; i--) {
            if (charArray[i] > charArray[maxIdx]) {
                maxIdx = i;
            } else if (charArray[i] < charArray[maxIdx]) {
                idx1 = i;
                idx2 = maxIdx;
            }
        }
        if (idx1 >= 0) {
            swap(charArray, idx1, idx2);
            return Integer.parseInt(new String(charArray));
        } else {
            return num;
        }
    }

    public void swap(char[] charArray, int i, int j) {
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
    }
}

复杂度分析

leetcode 670. 最大交换_第2张图片

你可能感兴趣的:(贪心,leetcode,算法,职场和发展)