[LeetCode] 2566. Maximum Difference by Remapping a Digit
You are given an integer num. You know that Bob will sneakily remap one of the 10 possible digits (0 to 9) to another digit.
Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num.
Notes:
When Bob remaps a digit d1 to another digit d2, Bob replaces all occurrences of d1 in num with d2.
Bob can remap a digit to itself, in which case num does not change.
Bob can remap different digits for obtaining minimum and maximum values respectively.
The resulting number after remapping can contain leading zeroes.
Example 1:
Input: num = 11891
Output: 99009
Explanation:
To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899.
To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890.
The difference between these two numbers is 99009.
Example 2:
Input: num = 90
Output: 99
Explanation:
The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0).
Thus, we return 99.
Constraints:
1 <= num <= 108
替換一個數字后的最大差值。
給你一個整數 num 。你知道 Danny Mittal 會偷偷將 0 到 9 中的一個數字 替換 成另一個數字。請你返回將 num 中 恰好一個 數字進行替換后,得到的最大值和最小值的差為多少。
注意:
當 Danny 將一個數字 d1 替換成另一個數字 d2 時,Danny 需要將 nums 中所有 d1 都替換成 d2 。
Danny 可以將一個數字替換成它自己,也就是說 num 可以不變。
Danny 可以將數字分別替換成兩個不同的數字分別得到最大值和最小值。
替換后得到的數字可以包含前導 0 。
Danny Mittal 獲得周賽 326 前 10 名,讓我們恭喜他。
思路
這是一道字符串的實現題。給的 input 是一個字符串,表示一個數字,需要把他變成一個最大的數和一個最小的數,然后求兩者的差值。首先我們思考最大的數是什么?是最高位盡量為 9,如果第一位已經為 9,那么就找到第一個不為 9 的digit,假如為 X,把所有的 X 都替換成 9。
又因為給的數字一定沒有前導 0,如果最高位出現的數字為 Y,我們把所有的 Y 都替換為 0 即可。
復雜度
時間O(n) - 遍歷字符串一次
空間O(1)
代碼
Java實現
class Solution {
public int minMaxDifference(int num) {
String str = String.valueOf(num);
int max = num;
for (char c : str.toCharArray()) {
if (c != '9') {
max = Integer.parseInt(str.replace(c, '9'));
break;
}
}
int min = Integer.parseInt(str.replace(str.charAt(0), '0'));
return max - min;
}
}

浙公網安備 33010602011771號