【问题标题】:How to merge two integer arrays in ascending order?如何按升序合并两个整数数组?
【发布时间】:2022-01-13 21:58:19
【问题描述】:

如何按升序合并两个数组? 我有下面的代码,我需要按升序合并这个数组,它应该在一个单独的方法中。所以在这种情况下,该方法应该返回{1, 4, 8, 9, 11, 12, 13}

public class MergingArrays {
    public static void main(String[] args) {
        int [] array1 = {4, 8, 12, 13};
        int [] array2 = {1, 9, 11};
        merge(array1, array2);
    } 
    public static int[] merge(int array1[], int array2[]) {

    }
}

【问题讨论】:

  • 最明显的方法是重复搜索两个数组的最小值,直到两个数组都为空。
  • return Stream.of(array1, array2).flatMapToInt(Arrays::stream).sorted().toArray();
  • 您的问题没有明确定义。您还没有说过如何处理重复的整数值。结果中是否仅存在不同的值?输入数组是否总是按顺序排序?

标签: java arrays merge


【解决方案1】:

假设您要合并两个已排序的数组,您可以这样做。

public static int[] merge(int array1[], int array2[]) {
    int i = 0, j = 0, k = 0;
    int size1 = array1.length;
    int size2 = array2.length;
    int[] result = new int[size1 + size2];

    while (i < size1 && j < size2) {
        if (array1[i] < array2[j]) {
            result[k++] = array1[i++];
        } else {
            result[k++] = array2[j++];
        }
    }

    // Store remaining elements
    while (i < size1) {
        result[k++] = array1[i++];
    }

    while (j < size2) {
        result[k++] = array2[j++];
    }
    
    return result;

}

【讨论】:

    【解决方案2】:
    public static int[] merge(int[] array1, int[] array2) {
            int totalElements = array1.length + array2.length, array2Index = 0;
            int[] toReturn = new int[totalElements];
    
            for (int i = 0; i < array1.length; i++) {
                toReturn[i] = array1[i];
            }
            for (int i = array1.length; i < totalElements; i++) {
                toReturn[i] = array2[array2Index++];
            }
    
            //Manual Ascending Array Sorting
            for (int i = 0; i < totalElements; i++) {
                for (int j = 0; j < totalElements; j++) {
                    if(toReturn[i] < toReturn[j]) {
                        int temp = toReturn[i];
                        toReturn[i] = toReturn[j];
                        toReturn[j] = temp;
                    }
                }
            }
            return toReturn;
        }
    

    【讨论】:

      【解决方案3】:

      你可以使用apache commons类和Collections类的排序功能

      import org.apache.commons.lang.ArrayUtils;
      import java.util.Collections;
      
      public class MergingArrays {
          public static void main(String[] args) {
              int [] array1 = {4, 8, 12, 13};
              int [] array2 = {1, 9, 11};
              merge(array1, array2);
          } 
          public static int[] merge(int array1[], int array2[]) {
          return Collections.sort(ArrayUtils.addAll(array1, array2));
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-02-13
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-28
        • 2019-09-03
        • 2011-04-05
        • 2020-08-01
        相关资源
        最近更新 更多