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:
The given number is in the range [0, ]
Solutions
My solution
Algorithm:
Let
num[i]denote the digit.Set
i = 0.While
num[i]is larger than any digit after it,++i.Find the largest digit after
num[i], saynum[j](if there are multiple largest digits, use the last one). Then swapnum[i]andnum[j].
A better solution
Same idea, but better implementation. The key is to store only the last occurrence of .
Credit: Java simple solution, O(n) time
Last updated