每日一题:力扣670. 最大交换
题意
给定一个非负整数,你至多可以交换一次数字中的任意两位。返回你能得到的最大值。
示例 1 :
输入: 2736
输出: 7236
解释: 交换数字2和数字7。
示例 2 :
输入: 9973
输出: 9973
解释: 不需要交换。
注意:
给定数字的范围是 [0, 108]
题解
class Solution {
public int maximumSwap(int num) {
char[] chs = (num+"").toCharArray();
char max1 = chs[0];
int len=chs.length;
Character[] tmp = new Character[len];
for(int i=0;i<len;i++) tmp[i] = chs[i];
Arrays.sort(tmp,new Comparator<Character>(){
public int compare(Character c1,Character c2){
return c2-c1;
}
});
int l,r;
for(int i=0;i<len;i++){
if(tmp[i]==chs[i]) continue;
else{
l=i;
r=len-1;
while(l<r){
if(chs[r]==tmp[i]) break;
r--;
}
char t= chs[i];
chs[i] = chs[r];
chs[r] = t;
break;
}
}
return Integer.parseInt(String.valueOf(chs));
}
}

相关推荐
最大公共字符串leetcode-LeetCode:每日力扣
最大公共字符串leetcode 力码 每日力扣 210428 输入:nums = [1,1,0,1,1,1] 输出:3 解释:前两位或后三位是连续的 1。 连续 1 的最大数量为 3。 示例 2: 输入:nums = [1,0,1,1,0,1] 输出:2 约束: 1 <= nums.length <= 105 nums[i] 是 0 或 1。 class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int maxNumOfConsecutiveOnes = 0; int currentNumOfConsecutiveOnes = 0; for(const auto& num : nums) { if(num == 1) { currentNumOfConsecutiveOnes++; if(currentNumOfConsecutiveOnes > maxNumOfConsecutiveOnes) { maxNumOfConsecutiveOnes = currentNumOfConsecutiv
leetcode卡-leetcode-[removed]LeetCode力扣每日一题
leetcode卡 LeetCode 力扣 打卡每天一题 坚持100天 梦开始的地方~
leetcode题库-LeetCode:LeetCode每日一题
leetcode题库 LeetCode 为了防止LeetCode隔天忘,建立了这个仓库,用来记录LeetCode每日一题的做题心得。
leetcode每日一题总结.zip
总结本人2020年秋招过程中的遇到的编程问题,总结清晰,列表清楚,最后签约华为。
力扣每日一题自动提交python脚本-保姆级使用教程,妈妈再也不用担心我每日一题断签
力扣每日一题自动提交python脚本-保姆级使用教程,妈妈再也不用担心我每日一题断签


