Leetcode leetcode 670. Maximum exchange

insert image description here

Topic link and description

https://leetcode.cn/problems/maximum-swap/

Given a non-negative integer, you can swap any two digits of the number at most once. Return the maximum value you can get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:

Input: 9973
Output: 9973
Explanation: No swap required.
Notice:

The range of the given number is [0, 10^8]

Key words: value exchange greedy

method one:

run screenshot

insert image description here

the code

To make the number the largest, it is easy to think of putting the larger numbers in the front row, and the smaller numbers in the back row. Traversing it once, take the largest n digits and compare them

Change the way of thinking, because the largest number must always be in front of the big one, and the small one in the back; and we can only take one, so we only need to find the largest number and exchange it with the front value that is smaller than the front


	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 = maxIdx; 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;
	}



end

Welcome to communicate in the comment area, check in every day, and rush! ! !

Guess you like

Origin blog.csdn.net/qq_35530042/article/details/126826327