package com.算法专练.力扣.最大交换;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author xnl
* @Description:
* @date: 2022/9/13 23:15
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int num = 2736;
System.out.println(solution.maximumSwap2(num));
}
/**
* 直接遍历,然后进行交换
* @param num
* @return
*/
public int maximumSwap(int num) {
char[] chars = String.valueOf(num).toCharArray();
int maxValue = 0;
for (int i = 0; i < chars.length; i++){
for (int j = 0; j < chars.length; j++){
swap(chars, i , j);
maxValue = Math.max(maxValue, Integer.parseInt(new String(chars)));
swap(chars, i , j);
}
}
return maxValue;
}
private void swap(char[] chars, int i , int j){
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
/**
* 贪心
* @param num
* @return
*/
public int maximumSwap2(int num) {
char[] chars = String.valueOf(num).toCharArray();
int maxIndex = chars.length - 1;
int idx1 = -1, idx2 = -1;
for (int i = chars.length - 1; i >= 0; i--){
if (chars[i] > chars[maxIndex]){
maxIndex = i;
} else if (chars[i] < chars[maxIndex]){
idx1 = i;
idx2 = maxIndex;
}
}
if (idx1 >= 0){
swap(chars, idx1, idx2);
return Integer.parseInt(new String(chars));
}
return num;
}
}
力扣:670. 最大交换
最新推荐文章于 2024-11-04 12:20:00 发布