-2

我正在尝试合并两个独立排序的数组以生成一个按升序排序的数组。这是我到目前为止所拥有的:

public static String [] mergeStrings(String [] x, String [] y) {
    String[] result = new String[x.length + y.length];
    int largest = (x.length > y.length) ? x.length : y.length;

    for (int i = 0; i < largest; i++){

    }
}

从这里出发的任何方向都会很棒。谢谢!

4

3 回答 3

0

如果您希望合并也修剪重复项

System.out.println(Arrays.toString(mergeStrings( // "5" repeats
        new String[] {"1", "5", "8"}, new String[] {"2", "5", "6", "9"})));

public static String [] mergeStrings(String [] x, String [] y) {
    List<String> mergedList = new ArrayList<String>();
    int xp = 0, yp = 0;
    while ( xp < x.length && yp < y.length){
        if (x[xp].compareTo(y[yp]) < 0) {
            mergedList.add(x[xp++]);
        } else if (x[xp].compareTo(y[yp]) > 0) {
            mergedList.add(y[yp++]);
        } else {
            mergedList.add(x[xp]);
            xp++; yp++;
        }
    }
    while (xp < x.length) {
        mergedList.add(x[xp++]);
    }
    while (yp < y.length) {
        mergedList.add(y[yp++]);
    }
    return mergedList.toArray(new String[0]);
}

输出

[1, 2, 5, 6, 8, 9]
于 2013-10-03T21:10:35.750 回答
-1

请参阅下面的评论。

public static String [] mergeStrings(String [] x, String [] y) {
    //You declared the array that has enough size to wraph both x and y arrays. Good.
    String[] result = new String[x.length + y.length];

    // get the size of the bigger array?
    int largest = (x.length > y.length) ? x.length : y.length; 

    //If x.length is bigger, this will iterate x.length times, y.length otherwise.. 
    for (int i = 0; i < largest; i++){ 
    //even if you used result[i]=x[i] you would be missing elements for y. 
    }
}

我认为您正在尝试做的是这样的事情:

  public static String[] mergeStrings(String[] x, String[] y) {
    //Declare the result string with the sum of sizes.
    String[] result = new String[x.length + y.length];
    //Assign `x` values to result.
    for (int i = 0; i < x.length; i++) {
      result[i] = x[i];
    }

    //Assign `y` values to result. Using resultIndex to start on the first empty position while `i` will be the index for the `y` array.
    for (int i = 0, resultIndex = x.length; i < y.length; i++, resultIndex++) {
      result[resultIndex] = y[i];
    }
    return result;
  }
于 2013-10-03T21:05:13.260 回答
-4
for (int i = 0, j = 0, k = 0; i < x.length || j < y.length; k++){
    if (j==y.length || (i!=x.length && x[i].compareTo(y[j]) <= 0)
        result[k] = x[i++];
    else
        result[k] = y[j++];
}
于 2013-10-03T20:49:26.520 回答