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. 最大交换
最新推荐文章于 2025-11-24 16:32:05 发布
本文探讨了一个寻找整数中两个数字交换后能获得的最大数值的问题,提供了两种解决方案:直接遍历交换和贪心策略。直接遍历交换通过两层循环遍历所有可能的交换组合,而贪心策略则在遍历过程中找到当前最大值和次大值进行交换,提高了效率。代码以Java实现,并在主函数中进行了测试。

635

被折叠的 条评论
为什么被折叠?



