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.
Thoughts
只允许swap两个数字, 让它能达到所有可能swap/不swap中最大. 由于都是正数, 那么让前面位数尽量大, 如果能swap, 意味着从前数第i位后面有比nums[i]更大的数且应挑选其中最大的. 因此用一个数组存储0~9每个数字在nums中最后出现的位置, 再从左往后遍历nums, 对于nums[i]从大往小搜索比nums[i]的位置靠后的, 搜到了swap返回即可.
Code
Analysis
时间复杂度O(N).
Last updated
Was this helpful?