670. Maximum Swap
package LeetCode_670 /** * 670. Maximum Swap * https://leetcode.com/problems/maximum-swap/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. Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. * */ class Solution { /* * solution: Array,Time complexity:O(n), Space complexity:O(1) * */ fun maximumSwap(num: Int): Int { val digits = num.toString().toCharArray() val map = IntArray(10) for (i in digits.indices) { map[digits[i] - '0'] = i } /* * array for saving last position of digit in this num, for example: 98368 map is: 0,0,0,2,0,0,3,0,4,0, mean: last position of 9 is 0, last position of 8 is 4, last position of 3 is 2, last position of 6 is 3 * */ for (i in digits.indices) { //For each position, //we check whether there exists a larger digit in this num (start from 9 to current digit) for (d in 9 downTo digits[i] - '0' + 1) { /* * for example: 2736, the position of largest digit (7) is 1, 1 is behind 0, so swap they are, * */ if (map[d] > i) { swap(digits, map[d], i) return String(digits).toInt() } } } //if no need swap, return original num return num } private fun swap(str: CharArray, start: Int, end: Int) { val temp = str[end] str[end] = str[start] str[start] = temp } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)