hdu 2016 data exchange output [JAVA]

data exchange output

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 124662    Accepted Submission(s): 46272


Problem Description
Input n (n<100) numbers, find the smallest number, swap it with the first number and output these numbers.
 

Input
There are multiple groups of input data, each group occupies a row, and the beginning of each row is an integer n, which represents the number of values ​​of this test instance, followed by n integers. n=0 means the end of the input, no processing is done.
 

Output
For each set of input data, output the sequence after the exchange, and each set of output occupies a row.
 

Sample Input
 
  
4 2 1 3 4 5 5 4 3 2 1 0
 

Sample Output
 
  
1 2 3 4 1 4 3 2 5


The water problem continues. . This question is actually to find the maximum value. In fact, a relatively efficient way to find the maximum value is the dichotomy method. Compare the two numbers to find the larger one, and then perform a two-phase comparison from the found numbers. ratio, until the last two numbers are compared to find the largest number. However, because the time complexity of the input of this question is fixed at O(n), two more variables min and minIndex are set to save the subscripts of the minimum and minimum values. These two variables can be obtained after the input data is completed. , so the total time complexity is also O(n).

AC code:

import java . util . Scanner ;

public class Main {
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext())
        { 
            int num = sc . nextInt (); 
            if ( num == 0 )
            {
                break;
            }
            int[] a = new int[num];
            int min = 0x3f3f3f3f;
            int minIndex = -1;
            for(int i = 0;i < num;i++)
            {
                int x = sc.nextInt();
                if(x < min)
                { 
                    min = x ; 
                    minIndex = i ;
                }
                a[i] = x;
            }
            int t = a[0];
            a[0] = min;
            a[minIndex] = t;
            for(int i = 0;i < num;i++)
            {
                if(i == num-1)
                {
                    System.out.print(a[i]);
                    break;
                }
                System.out.print(a[i]+" ");
            }
            System.out.println();
        }
    }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324610262&siteId=291194637