Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

Note:

  1. The given number is in the range [0, 108]

这道题给了一个数字,我们有一次机会可以置换该数字中的任意两位,让返回置换后的最大值,当然如果当前数字就是最大值,也可以选择不置换,直接返回原数。那么最简单粗暴的方法当然就是将所有可能的置换都进行一遍,然后更新结果 res,取其中较大的数字,这样一定会得到置换后的最大数字,这里使用了整型数和字符串之间的相互转换,参见代码如下:

解法一:

class Solution {
public:
int maximumSwap(int num) {
string str = to_string(num);
int res = num, n = str.size();
for (int i = ; i < n; ++i) {
for (int j = i + ; j < n; ++j) {
swap(str[i], str[j]);
res = max(res, stoi(str));
swap(str[i], str[j]);
}
}
return res;
}
};

下面这种解法是一种更优解,思路是这样的,由于希望置换后的数字最大,那么肯定最好的高位上的小数字和低位上的大数字进行置换,比如题目汇总的例子1。而如果高位上的都是大数字,像例子2那样,很有可能就不需要置换。所以需要找到每个数字右边的最大数字(包括其自身),这样再从高位像低位遍历,如果某一位上的数字小于其右边的最大数字,说明需要调换,由于最大数字可能不止出现一次,这里希望能跟较低位的数字置换,这样置换后的数字最大,所以就从低位向高位遍历来找那个最大的数字,找到后进行调换即可。比如对于 1993 这个数:

1 9 9 3

9 9 9 3  (back数组)

9 9 1 3

我们建立好back数组后,从头遍历原数字,发现1比9小,于是从末尾往前找9,找到后一置换,就得到了 9913。

解法二:

class Solution {
public:
int maximumSwap(int num) {
string res = to_string(num), back = res;
for (int i = back.size() - ; i >= ; --i) {
back[i] = max(back[i], back[i + ]);
}
for (int i = ; i < res.size(); ++i) {
if (res[i] == back[i]) continue;
for (int j = res.size() - ; j > i; --j) {
if (res[j] == back[i]) {
swap(res[i], res[j]);
return stoi(res);
}
}
}
return stoi(res);
}
};

下面这种解法建了十个桶,分别代表数字0到9,每个桶存该数字出现的最后一个位置,也就是低位。这样从开头开始遍历数字上的每位上的数字,然后从大桶开始遍历,如果该大桶的数字对应的位置大于当前数字的位置,说明低位的数字要大于当前高位上的数字,那么直接交换这两个数字返回即可,其实核心思路跟上面的解法蛮像的,参见代码如下:

解法三:

class Solution {
public:
int maximumSwap(int num) {
string str = to_string(num);
vector<int> buckets(, );
for (int i = ; i < str.size(); ++i) {
buckets[str[i] - ''] = i;
}
for (int i = ; i < str.size(); ++i) {
for (int k = ; k > str[i] - ''; --k) {
if (buckets[k] <= i) continue;
swap(str[i], str[buckets[k]]);
return stoi(str);
}
}
return num;
}
};

我们也可以进一步的优化空间,实际上只关注两个需要交换的位置即可,即高位上的小数字和低位上的大数字,分别用 pos1 和 pos2 指向其位置,均初始化为 -1,然后用一个指针 mx 指向低位最大数字的位置,初始化为 n-1,然后从倒数第二个数字开始往前遍历,假如 str[i] 小于 str[mx],说明此时高位上的数字小于低位上的数字,是一对儿潜在可以交换的对象(但并不保证上最优解),此时将 pos1 和 pos2 分别赋值为 i 和 mx;若 str[i] 大于 str[mx],说明此时 str[mx] 不是低位最大数,将 mx 更新为 i。循环结束后,若 pos1 不为 -1,说明此时找到了可以交换的对象,而且找到的一定是最优解,直接交换即可,参见代码如下:

解法四:

class Solution {
public:
int maximumSwap(int num) {
string str = to_string(num);
int n = str.size(), mx = n - , pos1 = -, pos2 = -;
for (int i = n - ; i >= ; --i) {
if (str[i] < str[mx]) {
pos1 = i;
pos2 = mx;
} else if (str[i] > str[mx]) {
mx = i;
}
}
if (pos1 != -) swap(str[pos1], str[pos2]);
return stoi(str);
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/670

类似题目:

Create Maximum Number

参考资料:

https://leetcode.com/problems/maximum-swap/

https://leetcode.com/problems/maximum-swap/discuss/107068/Java-simple-solution-O(n)-time

https://leetcode.com/problems/maximum-swap/discuss/107153/simple-c-using-stdstring-and-stdstoi

https://leetcode.com/problems/maximum-swap/discuss/107084/C%2B%2B-3ms-O(n)-time-O(n)-space-DP-solution

https://leetcode.com/problems/maximum-swap/discuss/107073/C%2B%2B-one-pass-simple-and-fast-solution%3A-1-3ms-O(n)-time

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 670. Maximum Swap 最大置换的更多相关文章

  1. LC 670. Maximum Swap

    Given a non-negative integer, you could swap two digits at most once to get the maximum valued numbe ...

  2. [LeetCode] Maximum Swap 最大置换

    Given a non-negative integer, you could swap two digits at most once to get the maximum valued numbe ...

  3. 670. Maximum Swap

    Given a non-negative integer, you could swap two digits at most once to get the maximum valued numbe ...

  4. 670. Maximum Swap 允许交换一个数 求最大值

    [抄题]: Given a non-negative integer, you could swap two digits at most once to get the maximum valued ...

  5. [LeetCode] Create Maximum Number 创建最大数

    Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum numb ...

  6. [array] leetcode - 53. Maximum Subarray - Easy

    leetcode - 53. Maximum Subarray - Easy descrition Find the contiguous subarray within an array (cont ...

  7. [LeetCode] 152. Maximum Product Subarray_Medium tag: Dynamic Programming

    Given an integer array nums, find the contiguous subarray within an array (containing at least one n ...

  8. 小旭讲解 LeetCode 53. Maximum Subarray 动态规划 分治策略

    原题 Given an integer array nums, find the contiguous subarray (containing at least one number) which ...

  9. [LeetCode] 325. Maximum Size Subarray Sum Equals k 和等于k的最长子数组

    Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...

随机推荐

  1. LeetCode 150:逆波兰表达式求值 Evaluate Reverse Polish Notation

    题目: 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰表达式. Evaluate the value of an arithm ...

  2. Java面试- JVM 内存模型讲解

    经常有人会有这么一个疑惑,难道 Java 开发就一定要懂得 JVM 的原理吗?我不懂 JVM ,但我照样可以开发.确实,但如果懂得了 JVM ,可以让你在技术的这条路上走的更远一些. JVM 的重要性 ...

  3. AdminLTE 3.0发布了

    在11月2日,作者正式发布了AdminLTE 3.0版本.该版本基于Bootstrap 4.x.使用Bootstrap 4.x的小伙伴可以愉快的使用AdminLTE. Github AdminLTE是 ...

  4. 大一结业项目之一(C#晨曦超市管理系统 )

                                             C#晨曦超市管理系统                            我现是湖南工程职业技术学院大一的学生,很快 ...

  5. 简单的python GUI例子

    写一个简单的界面很容易,即使是什么都不了解的情况下,这个文本转载了最简单的界面编写,下个文本介绍了TK的简单但具体的应用 在python中创建一个窗口,然后显示出来. from Tkinter imp ...

  6. 面试官都叫好的Synchronized底层实现,这工资开多少一个月?

    本文为死磕Synchronized底层实现第三篇文章,内容为重量级锁实现. 本系列文章将对HotSpot的synchronized锁实现进行全面分析,内容包括偏向锁.轻量级锁.重量级锁的加锁.解锁.锁 ...

  7. c++语法大全笔记(一)

    目录 一:初级知识   c++是一种中级语言,是c的扩充,是一种面向对象的程序设计语言,可以运行到多个平台.这里直接讲语法.   基础c++模板: #include <iostream> ...

  8. python实现罗汉塔破解方法

    主要使用函数的递归方法,考虑过程如下:n,a,b,c(n代表罗汉塔块数,a,b,c代表三块柱子)若n=1时,只需从a>>>c若n>1时,需要把上面n-1块从a移动到b,底下1块 ...

  9. Java自学-集合框架 LinkedList

    Java集合框架 LinkedList 序列分先进先出FIFO,先进后出FILO FIFO在Java中又叫Queue 队列 FILO在Java中又叫Stack 栈 示例 1 : LinkedList ...

  10. C#中一行代码实现18位数字时间戳转换为DateTime

    场景 存取的时间戳数据为: 636728674347302002 怎样将其转换为DateTime时间. 目前大多数的策略是,转换成string,然后 DateTime dateTimeStart = ...