(算法分析Week10)Maximum Swap[Meduim]
来源:互联网 发布:mysql root 权限不足 编辑:程序博客网 时间:2024/06/07 13:40
670. Maximum Swap[Medium]
题目来源
Description
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.
Example1:
Input: 2736Output: 7236Explanation: Swap the number 2 and the number 7.
Example2:
Input: 9973Output: 9973Explanation: No swap.
The given number is in the range [0, 10^8]
Solution
给出一个数字,可以选择其中任意两个数交换一次,使得交换完的数是所有交换选择中最大的那个。
显而易见,肯定是把所有数字中最大的那个放在最高位,如果高位已经不能再大,那就次一位,以此类推。
思路就是用一个整数数组把整个数字按位存放,然后从第一位开始向后比较,找出从当前数字往后找比它大的最大值,然后交换。最后再把数组转成string返回即可。
要注意一些比较坑的地方,比如输入1993,如果从1开始往后找到第一个9就返回交换,那就得不到期望的9913的结果。所以判断条件不能是大于,而应该是大于等于,目的是找到处于相对最低位的最大值。
Complexity analysis
O(n²)
Code
class Solution {public: int maximumSwap(int num) { vector<int> result; while (num) { result.push_back(num % 10); num /= 10; } bool flag = false; for (int i = result.size() - 1; i >= 0 && flag == false; i--) { int index = i; int max = result[i]; for (int j = i - 1; j >= 0 && flag == false; j--) { if (max <= result[j]) { max = result[j]; index = j; } } if (result[i] < result[index]) { int temp = result[i]; result[i] = result[index]; result[index] = temp; flag = true; } } int t = 0; for (int i = result.size() - 1; i >= 0; i--) { t *= 10; t += result[i]; } return t; }};
Result
阅读全文
0 0
- (算法分析Week10)Maximum Swap[Meduim]
- (算法分析Week10)ZigZag Conversion[Medium]
- Week10 53. Maximum Subarray
- (算法分析Week10)Letter Combinations of a Phone Number[Medium]
- LeetCode算法题——Maximum Swap
- week10-leetcode #24-Swap-Nodes-in-Pairs
- week10
- 算法分析:Maximum Subsequence Sum
- Maximum Subarray (算法分析week2)
- [LeetCode-Algorithms-24] "Swap Nodes in Pairs" (2017.11.7-WEEK10)
- Leetcode--670. Maximum Swap
- 670. Maximum Swap
- 670. Maximum Swap
- leetcode-670-Maximum Swap
- leetcode 670. Maximum Swap
- 670. Maximum Swap
- LeetCode 670. Maximum Swap
- 670. Maximum Swap(Java)
- 中国地图SVG绘制
- CentOS 6&7 安装使用多个GCC版本(GCC4.9,GCC5.3,GCC6.2)
- 前通用汽车高管:我们正接近汽车时代的终结 | 行业
- 担心无人驾驶不安全?事实上它比人类司机靠谱的多 | 讨论
- 霍金:人工智能不会毁灭人类,反而有助于疾病医疗 | 观点
- (算法分析Week10)Maximum Swap[Meduim]
- Android项目APK打包And多渠道打包
- 文字上下无缝滚动(Jquery)
- (案例五)将数据保存在MongoDB中
- Sys.SysProcesses 系统表是一个很重要的系统视图,主要用来定位与解决Sql Server的阻塞和死锁
- CentOS7下的网络设定方法
- A/ B测试——你做的是错的
- poj 3436 网络流基础题
- Excel(xls)转json工具