LeetCode 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. 

Example 2:

Input: 9973
Output: 9973
Explanation: No swap. 

Note:

  1. The given number is in the range [0, 108]

题解:

想要组成最大的数字,就是要把尽量开头的digit换成后面比他大的最大digit. 若这个最大digit有重复, 去最右侧的那个.

所以先把么个digit出现的最优index记录下来. 从头开始走原有digit, 若后面出现了比他大的digit, 取后面最大的digit与原有digit调换得到结果.

Time Complexity: O(n). n是原有num digits的位数.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int maximumSwap(int num) {
 3         char [] digits = Integer.toString(num).toCharArray();
 4         
 5         int [] lastInd = new int[10];
 6         for(int i = 0; i<digits.length; i++){
 7             lastInd[digits[i]-'0'] = i;
 8         }
 9         
10         for(int i = 0; i<digits.length; i++){
11             for(int k = 9; k>digits[i]-'0'; k--){
12                 if(lastInd[k] > i){
13                     char temp = digits[i];
14                     digits[i] = digits[lastInd[k]];
15                     digits[lastInd[k]] = temp;
16                     return Integer.valueOf(new String(digits));
17                 }
18             }
19         }
20         return num;
21     }
22 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/7766573.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值