Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created September 3, 2017 02:42
Show Gist options
  • Select an option

  • Save cixuuz/e6610f6f6f026c04bf15d22d3eff2aa9 to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/e6610f6f6f026c04bf15d22d3eff2aa9 to your computer and use it in GitHub Desktop.
[670. Maximum Swap] #leetcode
class Solution {
public int maximumSwap(int num) {
String temp = Integer.toString(num);
int[] nums = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) nums[i] = temp.charAt(i) - '0';
boolean flag = false;
List<Integer> maxIdx = new ArrayList<Integer>();
for (int i = 0; i < nums.length-1; i++) {
int max=0;
for (int j = i+1; j < nums.length; j++) {
if (nums[j] > nums[i]) {
if (nums[j] > max) {
max = nums[j];
maxIdx = new ArrayList<Integer>();
maxIdx.add(j);
} else if (nums[j] == max) {
maxIdx.add(j);
}
}
}
if (max != 0) {
int res = 0;
StringBuilder strNum;
for (Integer idx : maxIdx) {
nums[idx] = nums[i];
nums[i] = max;
strNum = new StringBuilder();
for (int n : nums) strNum.append(n);
res = Math.max(res, Integer.parseInt(strNum.toString()));
nums[i] = nums[idx];
nums[idx] = max;
}
return res;
}
}
return num;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment