hdu 2019 series in order! 【Merge】

The numbers are in order!

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


Problem Description
There are n (n<=100) integers, which have been arranged in ascending order. Now give another integer x, please insert this number into the sequence, and make the new sequence still in order.
 

Input
The input data contains multiple test instances, each set of data consists of two rows, the first row is n and m, and the second row is an ordered sequence of n numbers. Both n and m are 0 to indicate the end of the input data, and this line does not process it.
 

Output
For each test instance, output the sequence after inserting the new element.
 

Sample Input
 
  
3 3 1 2 4 0 0


There are many ways to do it. The merge I use here has a time complexity of O(n+m). Since m is always 1, the final time complexity is O(n).

import java.util.Scanner;

public class Main {
    public  static int[]  merge(int[] a,int[] b)
    {
        int[] c = new int[a.length+b.length];
        int i = 0;
        int j = 0;
        int k = 0;
        while(i < a.length && j < b.length)
        {
            if(a[i] <= b[j])
            {
                c[k++] = a[i++];
            }
            else
            {
                c[k++] = b[j++];
            }
        }
        if(i == a.length)
        {
            while(j < b.length)
            {
                c[k++] = b[j++];
            }
        }
        else if(j == b.length)
        {
            while(i < a.length)
            {
                c[k++] = a[i++];
            }
        }
        return c;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext())
        {
            int n = sc.nextInt();
            int m = sc.nextInt();
            if(n == 0 && m == 0)
            {
                break;
            }
            int[] a = new int[n];
            int[] b = new int[1];
            for(int i = 0;i < n;i++)
            {
                a[i] = sc.nextInt();
            }
            b[0] = m;
            int c[] = merge(a, b);
            for(int i = 0;i < c.length;i++)
            {
                if(i == c.length-1)
                {
                    System.out.print(c[i]);
                    break;
                }
                System.out.print(c[i]+" ");
            }
            System.out.println();
        }
    }

}

Guess you like

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