LeetCode算法题——Maximum Swap
来源:互联网 发布:阿里云 连接 腾讯云 编辑:程序博客网 时间:2024/06/16 06:20
题目概述
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:Input: 2736Output: 7236Explanation: Swap the number 2 and the number 7.
分析
希望得到最大的数字,最理想的情况是实现高位小数字和低位大数字的互换。具体实施的办法:
- 得到高位数字:设计外层循环,从高位到低位进行遍历
- 得到低位大数字:使用一个桶,存储每个数字从左到右最后出现的位置,之后设计内层循环,优先从获取大数字的位置开始遍历
桶的设计比较容易,因为一共只有0~9十个数字,设计一个长度为10的数组即可。在存入桶之前,使用string库里自带的函数可以方便地将整数转为string。
具体代码如下:
int maximumSwap(int num) { string str = to_string(num); vector<int> bucket(10, 0); for (int i = 0; i < str.size(); i++) bucket[str[i] - '0'] = i; // 记录每个数字所在的最右位置 for (int i = 0; i < str.size(); i++) for (int j = 9; j > str[i] - '0'; j--) { // 从大桶开始遍历 if (bucket[j] <= i) continue; // 大桶数字位置大于当前数字的位置,说明低位数字大于当前高位数字 swap(str[i], str[bucket[j]]); return stoi(str); } return num;}
时间复杂度为O(10*N) = O(N),取决于传入整数的长度;空间复杂度为O(N),只需要考虑桶和字符串的长度
总结
- 桶排序在这种元素范围有限(0~9)的情况下比较方便
- 本质上两层循环设计属于贪心算法的体现
- string库中部分类型转换函数的使用
阅读全文
0 0
- LeetCode算法题——Maximum Swap
- Leetcode--670. Maximum Swap
- leetcode-670-Maximum Swap
- leetcode 670. Maximum Swap
- LeetCode 670. Maximum Swap
- LeetCode-Maximum Swap
- leetcode 670 Maximum Swap
- leetCode-Maximum Swap
- leetcode 670. Maximum Swap
- LeetCode算法题——24. Swap Nodes in Pairs
- LeetCode-Medium-Java-Maximum Swap
- Leetcode之Maximum Swap 问题
- 数据结构与算法[LeetCode]—Maximum Subarray
- (算法分析Week10)Maximum Swap[Meduim]
- LeetCode刷题 | 670. Maximum Swap | 中等难度 for循环处理题
- leetcode第24题——**Swap Nodes in Pairs
- LeetCode——Maximum Subarray
- LeetCode——Maximum Subarray
- SQL server sequence构造自定义自增主键
- webpack 3.X 安装与配置
- Oracle trunc()函数的用法
- dubbo通信协议之对比
- 批量开洞
- LeetCode算法题——Maximum Swap
- 拉丁矩阵问题
- JAVA项目中发布WebService服务—简单实例
- 二叉树的构建 遍历 以及 根据 先序遍历 中序遍历 来构建二叉树
- java学习随手记
- spark读取hdfs异常记录
- 20、状态模式(State)
- 大话设计模式读书笔记之单例模式
- 正则表达式 -转义字符