方法一: 模拟找到需要交换的两个数
注意:
- 初始化两个index坐标时应为-1,若为改变过则无需交换
- 找最大值的思路是先将数组排序,在比较最大值的同时并比较元素中元素在排序数组中的排位是否对应,对应则跳过
- 交换时两个坐标maxindex需要大于changeIndex才能满足条件,即大的数不能往低位交换
臭长代码:
class Solution {
public int maximumSwap(int num) {
return byString(num);
}
public int byString(int num){
String str=num+"";
char[] temp=str.toCharArray();
char[] arr=str.toCharArray();
int maxindex=-1,changeIndex=-1,max=0;
HashMap<Character,Integer> map=new HashMap<>();
Arrays.sort(arr);
for(int i=0;i<temp.length;i++){
if(max<=temp[i]-'0'&& temp[i]!=arr[temp.length-i-1] ){
maxindex=i;
max=temp[i]-'0';
}
}
for(int i=0;i<temp.length;i++){
if(max>temp[i]-'0'){
changeIndex=i;
break;
}
}
if(maxindex>changeIndex && maxindex!=-1 && changeIndex!=-1 ){
char c=temp[maxindex];
temp[maxindex]=temp[changeIndex];
temp[changeIndex]=c;
}
String t=new String(temp);
return Integer.valueOf(t);
}
}
方法二: 记忆化区间最大值
- 使用临时数组存储对应子区间最大值的下标
- 当子区间中的最大下标的值不和最大值相同,则交换两个下标对应的值
class Solution {
public int maximumSwap(int num) {
List<Integer> list = new ArrayList<>();
while (num != 0) {
list.add(num % 10); num /= 10;
}
int n = list.size(), ans = 0;
int[] idx = new int[n];
for (int i = 0, j = 0; i < n; i++) {
if (list.get(i) > list.get(j)) j = i;
idx[i] = j;
}
for (int i = n - 1; i >= 0; i--) {
if (list.get(idx[i]) != list.get(i)) {
int c = list.get(idx[i]);
list.set(idx[i], list.get(i));
list.set(i, c);
break;
}
}
for (int i = n - 1; i >= 0; i--) ans = ans * 10 + list.get(i);
return ans;
}
}