Topics
Leetcode Source Problem
Give a non-negative integer [0, 10^8], and the maximum value to be obtained after swapping at most.
Example 1:
input:2736
output:7236
Explanation:swap the number 2 and the number 7.
Example 2:
input:9973
output:9973
Explanation:no swap. Ideas
Space-time complexity of O (n)
① in order to facilitate the interchange, it is necessary to remember the digits of the number of the interchange, after which the result num = Num-high * Ten ^ high digit-low * ten ^ low digit
② uses a list of bits[] to divide num into a single bit storage, corresponding to the subscript i is the number corresponding to the digit
Bits[i]: Number representing the number I corresponds
For example, integer num = 2736,
bits[0] = 6,bits[1] = 3,bits[2] = 7,bits[2] = 2
③ with dynamic planning generation list dp[] record some subscripts for fast finding the corresponding digits of the number exchanged
Dp[i]: digit that represents the maximum value in the [0, i-1] bit of num
Transfer equation:
For example, the integer num = 2736,
dp[1] = 0, 10 bit 3 to the right maximum is the digit 6, the corresponding digit is 0
dp[2] = 0, the Hundred 7 right maximum is the single digit 6
dp[3] = 2, thousands 2 to the right maximum is the Hundred 7, Hundreds of the corresponding digits are 2
Note: Bits[i] stores a number , and dp[i] stores the digits
Use: Through Dp[i] to obtain a number of digits, through Bits[dp[i]] "to obtain the number corresponding to the digital, convenient step ① calculation
④ greedy ideas, as far as possible to the high-level of the exchange of larger numbers
Start scanning from the highest bit, if the value of a single digit is less than the maximum value in its low number, that is, the two numbers can be exchanged to produce a result code
Class Solution {public:int maximumswap (int num) {//stores each digit bit[0] represents the lowest bit vector<int> bits;
int tmp = num;
while (TMP) {int bit = tmp% 10;
Bits.push_back (bit);
TMP/= 10;
}//Dp[i]: subscript, boundary dp[0] is initialized to 0 int len = bits.size () than the maximum value in all digits in the bit low position;
Vector<int> DP (LEN);
for (int i = 0; i < len; i++) {if (i = = 0) Dp[i] = 0;
else if (bits[i-1] > Bits[dp[i-1]]) dp[i] = i-1;
else dp[i] = dp[i-1];
}//from the highest bit to the lowest bit, if the first bit is less than the maximum value in its low, i.e. num[i] < Num[dp[i]], then displace the two bits to get the maximum value int res = num;
for (int highbit = len-1; highbit >= 0; highbit--) {int lowbit = Dp[highbit]; if (Bits[highbit] < Bits[lowbit]) {//Displace two-bit digital res = num-bits[highbit] * POW (HIGHB
It)-bits[lowbit] * POW (ten, lowbit) + bits[lowbit] * POW (Ten, highbit) + bits[highbit] * POW (lowbit);
Break
}} return res; }
};