You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求完成Java两数组合并程序并提供详细解题步骤

Hey there! Let's tackle this array merging problem step by step. Looking at your existing code, it seems like both jsaList1 and jsaList2 are sorted in ascending order—perfect, because we can use an efficient two-pointer approach instead of the simpler (but less optimal) "merge then sort" method.

解题核心思路

Our goal is to combine two arrays into one that contains all elements, and if the inputs are sorted, we want the result to stay sorted too. The two-pointer method runs in O(n+m) time (where n and m are the lengths of the two input arrays), which is way faster than merging first then sorting (which takes O((n+m)log(n+m)) time).

Here's the breakdown of how it works:

  • Initialize three pointers: one for each input array (i for jsaList1, j for jsaList2) and one for the result array (k).
  • Create a result array with a length equal to the sum of the two input arrays—this ensures we have enough space for all elements.
  • Loop through both arrays, comparing the elements at the current pointer positions. Add the smaller (or equal) element to the result array, then move the corresponding pointer forward.
  • Once one array is fully traversed, append all remaining elements from the other array directly to the result (since the input arrays are sorted, these leftover elements are all larger than everything already in the result).
完整Java代码实现
public class Lab18bvst {
    public static void main(String[] args) {
        int[] jsaList1 = {101, 105, 115, 125, 145, 165, 175, 185, 195, 225, 235, 275, 305, 315, 325, 335, 345, 355, 375, 385};
        // I filled in a sample sorted jsaList2 for you—replace this with your actual array content
        int[] jsaList2 = {110, 120, 130, 150, 160, 170, 190, 200, 210, 240, 250, 260, 280, 290, 300, 320, 340, 360, 370, 390};
        
        // Step 1: Create result array with enough space
        int[] mergedArray = new int[jsaList1.length + jsaList2.length];
        
        // Step 2: Initialize pointers
        int i = 0; // Tracks position in jsaList1
        int j = 0; // Tracks position in jsaList2
        int k = 0; // Tracks position in mergedArray
        
        // Step 3: Compare elements and build merged array
        while (i < jsaList1.length && j < jsaList2.length) {
            if (jsaList1[i] <= jsaList2[j]) {
                mergedArray[k] = jsaList1[i];
                i++; // Move pointer in jsaList1 forward
            } else {
                mergedArray[k] = jsaList2[j];
                j++; // Move pointer in jsaList2 forward
            }
            k++; // Always move the result pointer forward
        }
        
        // Step 4: Add remaining elements from jsaList1 (if any)
        while (i < jsaList1.length) {
            mergedArray[k] = jsaList1[i];
            i++;
            k++;
        }
        
        // Step 5: Add remaining elements from jsaList2 (if any)
        while (j < jsaList2.length) {
            mergedArray[k] = jsaList2[j];
            j++;
            k++;
        }
        
        // Print the merged array to verify the result
        System.out.println("Merged array:");
        for (int num : mergedArray) {
            System.out.print(num + " ");
        }
    }
}
代码逐行解释
  • Result array initialization: int[] mergedArray = new int[jsaList1.length + jsaList2.length]; ensures we don't run into index out-of-bounds errors by allocating exactly enough space for all elements.
  • Two-pointer loop: The while loop runs until one of the input arrays is fully processed. We compare elements at the current pointer positions and add the smaller one to the result—this keeps the merged array sorted.
  • Leftover element handling: The two final while loops clean up any remaining elements from the unprocessed array. Since the input arrays are sorted, these elements are all larger than everything already in the result, so we can just append them directly.
  • Verification print: The enhanced for loop prints out the merged array so you can easily check if it's correct.
备选方案:合并后排序(适用于无序输入数组)

If your jsaList2 isn't sorted, the two-pointer method won't work. Instead, we can merge the arrays first then sort the result. This is simpler to code but less efficient—great for quick solutions when speed isn't critical.

import java.util.Arrays;

public class Lab18bvst {
    public static void main(String[] args) {
        int[] jsaList1 = {101, 105, 115, 125, 145, 165, 175, 185, 195, 225, 235, 275, 305, 315, 325, 335, 345, 355, 375, 385};
        int[] jsaList2 = {110, 120, 130, 150, 160, 170, 190, 200, 210, 240, 250, 260, 280, 290, 300, 320, 340, 360, 370, 390};
        
        // Create result array
        int[] mergedArray = new int[jsaList1.length + jsaList2.length];
        
        // Copy jsaList1 into the start of mergedArray
        System.arraycopy(jsaList1, 0, mergedArray, 0, jsaList1.length);
        
        // Copy jsaList2 into the end of mergedArray
        System.arraycopy(jsaList2, 0, mergedArray, jsaList1.length, jsaList2.length);
        
        // Sort the merged array
        Arrays.sort(mergedArray);
        
        // Print the result
        System.out.println("Merged and sorted array:");
        for (int num : mergedArray) {
            System.out.print(num + " ");
        }
    }
}

Notes on this alternative:

  • System.arraycopy is a built-in Java method that copies arrays more efficiently than manual loops.
  • Arrays.sort uses an optimized sorting algorithm (dual-pivot quicksort for primitive types) that's fast enough for most use cases.

内容的提问来源于stack exchange,提问作者Jeehyun Yoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:43:09