I saw an interview question asked by someone else from the German question and did it:
Interview question: Obtain the relative maximum value when the number is switched.
An interview question encountered some time ago:
Here is a number, which allows you to select two digit exchange locations. Each number can only be exchanged once. Please switch to the highest possible value and write an algorithm (note that there are repeated numbers ).
For example:
13792-> 97312 (each number can only be exchanged once, so you cannot get 97321. Try to make it OK)
5881-> 8851 (exchange 5 and the second 8, do not exchange for 8581)
------------------- Split line --------------------
Let me also talk about the idea:
1. Start with the first number and find the largest number from the remaining number that has not been exchanged. If the maximum number is repeated, It is exchanged with the last repeated number. This iteration ends until half of the numbers have been exchanged (because two switches are used for each exchange.
The time complexity is O (n ^ 2), and there is no linear time solution.
# Include <stdio. h> # include <memory. h> # define N 100int A [N]; // stores the number bool B [N]; // records whether the number has been exchanged with int main (void) {int I, j, t, n; int nMax, nMaxIndex, nTemp; freopen ("in.txt", "r", stdin); // redirection for testing data while (scanf ("% d ", & n )! = EOF) {memset (A, 0, sizeof (A); memset (B, 0, sizeof (B); for (I = 1; I <= n; ++ I) {scanf ("% d", & A [I]);} t = n/2; // you only need to swap half of the numbers for (I = 1; I <= t; ++ I) {if (false = B [I]) {nMax = A [I]; nMaxIndex = I; for (j = I + 1; j <= n; ++ j) {if (false = B [j] & A [j]> = nMax) // use A case where the value greater than or equal to processing duplicate numbers {nMax = A [j]; nMaxIndex = j ;}} if (nMax! = A [I]) // if the two numbers to be exchanged are equal, that is, no exchange is required. If no switch is wasted, {B [I] = true; B [nMaxIndex] = true; nTemp = A [I]; A [I] = A [nMaxIndex]; A [nMaxIndex] = nTemp ;}}// output result: for (I = 1; I <= n; ++ I) {printf ("% d", A [I]);} printf ("\ n");} return 0 ;}