• LeetCode 670. Maximum Swap


    原题链接在这里:https://leetcode.com/problems/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:

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

    题解:

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

    It is about how to get the index of largest digit after current one.

    所以先把么个digit出现的last index记录下来.

    Iterating num, check from max = 9 to check if max last occurance index is after i. If yes, swap.

    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 }

    类似Remove K Digits.

  • 相关阅读:
    李超线段树板子
    蒟蒻的平衡树学习笔记(=.=
    P2254 [NOI2005] 瑰丽华尔兹
    表达式求值学习笔记
    二分和一些其它算法的奇妙组合
    《wwx》的学习总结(题解)
    set的学习笔记
    题解 P4913 【深基16.例3】二叉树深度
    AGC002F Leftmost Ball
    CSP&&NOIP2020 游记
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7766573.html
Copyright © 2020-2023  润新知