670. Maximum Swap(Java)
来源:互联网 发布:papi酱上海话 知乎 编辑:程序博客网 时间:2024/04/28 19:39
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: 2736Output: 7236Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973Output: 9973Explanation: No swap.
Note:
The given number is in the range [0, 10的8次方]
class Solution { public int maximumSwap(int num) { char[] digit = Integer.toString(num).toCharArray(); // record the last position of digit 0 ~ 9 in this num. // index 为每个位上数字的大小,loc[index]为在digit中最后出现index值的位置 int[] loc = new int[10]; for (int i = 0; i < digit.length; i ++) { loc[digit[i] - '0'] = i; } for (int i = 0; i < digit.length; i ++) { for (int j = 9; j > digit[i] - '0'; j --) { // loc[j]表示大数所在位数,i表示小数所在位数,只有当大数位数在小数位数的后面时才互换 if (i < loc[j]) { char tmp = digit[i]; digit[i] = digit[loc[j]]; digit[loc[j]] = tmp; return Integer.valueOf(new String(digit)); } } } return num; }}
阅读全文
0 0
- 670. Maximum Swap(Java)
- Leetcode--670. Maximum Swap
- 670. Maximum Swap
- 670. Maximum Swap
- leetcode 670. Maximum Swap
- 670. Maximum Swap
- LeetCode 670. Maximum Swap
- 670. Maximum Swap
- 670. Maximum Swap
- leetcode 670. Maximum Swap
- 670. Maximum Swap
- LeetCode-Medium-Java-Maximum Swap
- leetcode-670-Maximum Swap
- LeetCode670. Maximum Swap
- LeetCode-Maximum Swap
- leetcode 670 Maximum Swap
- leetCode-Maximum Swap
- LeetCode670. Maximum Swap
- quartz定时设置代码
- hbase学习教程(一):hbase的概述和hbase架构及基本组件
- 刷题训练——懒人选座位
- 2017.09.27工作日记
- 233 Matrix HDU
- 670. Maximum Swap(Java)
- 几种常见的网页布局形式
- Java 课堂笔记 2
- C++重定义
- Java后台框架篇--Struts2.0核心与工作原理
- Happy 2006 POJ
- 几种进程间的通信方式
- Redis系列之Redis主从同步,读写分离(二)
- javaweb项目 基于jsp+servlet的 个人博客网站