gpt4 book ai didi

java - 您如何处理这种合并数组方法?

转载 作者:行者123 更新时间:2023-12-01 22:18:03 24 4
gpt4 key购买 nike

各位专业人士,您好,

I was taking a test online coding challenge in a website. They provide me 2 program. I had done a program and second one is below.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution{

/*
* Complete the function below.
*/

/* Write your custom functions here */
static void mergeArray(int []a, int []b, int M ){

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int _a_cnt = 0;
int[] _a = new int[100001];
int[] _b = new int[200002];

try {
_a_cnt = sc.nextInt();
}catch (Exception e) {
System.out.println("Here: " + e.getMessage());
}

for( int i = 0;i < _a_cnt;i++ ){
_a[i] = sc.nextInt();
}

for( int i = 0;i < _a_cnt;i++ ){
_b[i] = sc.nextInt();
}

mergeArray(_a ,_b,_a_cnt);

for( int i = 0;i < 2 * _a_cnt;i++ ){
System.out.print(_b[i] + " ");
}
}
}

根据我的理解,我们需要编写一段代码来合并两个数组(已经在那里定义了 int []a, int []b, int M),我们应该将其返回主程序。这是我的问题我们如何合并这两个数组并返回它?是否有任何技术可以在java中处理内存引用(如C# out,ref关键字)?

规则:您不应修改 main 函数。

这是一些输出:

示例输入:

              a = {3,5,6,9,12,14,18,20,25,28}
b = {30,32,34,36,38,40,42,44,46,48 }

预期输出:

{3,5,6,9,12,14,18,20,25,28,30,32,34,36, 38,40,42,44,46,48}

最佳答案

从数组的长度可以很明显地看出,任务是将第一个数组合并到第二个数组中(因为第二个数组的长度是第一个数组的两倍,但它们都必须包含相同数量的输入值)。

没那么复杂:

static void mergeArray(int[] a, int[] b, int n) {
for (int i = n*2 - 1, x = n - 1, y = n - 1; i >= 0; i--)
b[i] = x >= 0 && a[x] >= b[y] ? a[x--] : b[y--];
}

经过测试并有效。

关于java - 您如何处理这种合并数组方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30590121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com