2021-09-01

小米第一道题

给定两个有序整数数组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--];
    }
}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值