670. Maximum Swap
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:
- The given number is in the range [0, 108]
只交换一次整数中的两个数,获得最大的值
思路:从高位向低扫描,如果后面某位的数大于等于当前位的值,交换位置后即得到最大值。
1 public int maximumSwap(int num) { 2 // 从高位向低扫描,如果后面某位的数大于等于当前位的值,交换位置后即得到最大值 3 char[] dig = String.valueOf(num).toCharArray(); 4 int maxIndex = 0; 5 while (maxIndex < dig.length - 1) { 6 int newMaxIndex = maxIndex; 7 for (int i = maxIndex + 1; i < dig.length; i++) { 8 if (dig[newMaxIndex] <= dig[i]) newMaxIndex = i; 9 } 10 if (newMaxIndex != maxIndex && dig[newMaxIndex] != dig[maxIndex]) { 11 char temp = dig[newMaxIndex]; 12 dig[newMaxIndex] = dig[maxIndex]; 13 dig[maxIndex] = temp; 14 return Integer.valueOf(new String(dig)); 15 }else maxIndex++;//当前maxIndex的后面没有大于等于它的数字了 16 } 17 return num; 18 }
分类:
leetcode_array
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!