小米第一道题
给定两个有序整数数组A和B,将B合并到A中,使得A成为一个有序数组。
说明:
1.初始化A和B的元素数量分别为m和n。
2.A有足够的空间(空间大小或等于m+n)来保存B中的元素
3.默认升序
输入描述:
数组A,以及数组A元素数量
数组B,以及数组B元素数量
A=[1,6,7,0,0,0], m=3
B=[2,4,6], n=3
输出描述
合并后的数组A
A=[1,2,4,6,6,7];
样例输入:
m=2,n=2
1,3
2,4
样例输出:
1 2 3 4
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
public class bishi {
static ArrayList res= new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.nextLine();
String s1 = str1.split(",")[0].split("=")[1];
String s2 = str1.split(",")[1].split("=")[1];
int m = Integer.valueOf(s1).intValue();
int n = Integer.valueOf(s2).intValue();
String str2 = sc.nextLine();
String[] s3 = str2.split(",");
String str3 = sc.nextLine();
String[] s4 = str3.split(",");
int[] nums1 = new int[m+n];
int[] nums2 = new int[n];
for(int i = 0; i < m; i++){
nums1[i] = Integer.valueOf(s3[i]).intValue();
}
for(int i = 0; i < n; i++){
nums2[i] = Integer.valueOf(s4[i]).intValue();
}
merge(nums1, m, nums2, n);
for (int i=0;i<nums1.length-1;i++){
System.out.print(nums1[i]+" " );
}
System.out.print(Arrays.toString(nums1));
}
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int p = m-- + n-- - 1;
while (m >= 0 && n >= 0) {
nums1[p--] = nums1[m] > nums2[n] ? nums1[m--] : nums2[n--];
}
while (n >= 0) {
nums1[p--] = nums2[n--];
}
}
}