【问题标题】:Best way to unifies several arrays into one sorted array将多个数组统一为一个排序数组的最佳方法
【发布时间】:2015-03-29 20:02:04
【问题描述】:

以下内容来自面试:

对于有序数组的数组,写一个函数来统一 数组到一个排序数组中。

我考虑过使用HashSet<E>,并为每个数组添加一个完整的数组,只有一个顺序(我不知道,但它必须是预先编写的方法?!),但我可以发誓有一个简单的解决方案......

有什么建议吗?

谢谢!

【问题讨论】:

  • 这将是归并排序的merge步骤。
  • @RohitJain 你能编写这个例子吗?谢谢...
  • 试一试怎么样。这是我给出的一个重要提示。请不要到处找代码。
  • @RohitJain 我知道并且我很感激,我知道下降解决方案将是 n 数组的合并排序 n-1 次,但是是否有结构方法可以让 HashSet 作为缩短的优势未来的代码?

标签: java arrays hashset


【解决方案1】:

您基本上想从合并两个(可以扩展到更多)数组的合并排序算法中窃取一个方法。这是一个示例(用于合并 2 个数组):

private static int[] merge(int[] left, int[] right) {
    int lengthResult = left.length + right.length;
    int[] result = new int[lengthResult];
    int indexL=0, indexR=0, indexResult = 0;

    //while there are elements left in left or right
    while(indexL < left.length || indexR < right.length){

        //BOTH left and right still have elements 
        if(indexL < left.length && indexR < right.length){
            //if the left item is greater than right item
            if(left[indexL] <= right[indexR]){
                result[indexResult] = left[indexL];
                indexL++;
                indexResult++;
            }else{
                result[indexResult] = right[indexR];
                indexR++;
                indexResult++;
            }
        //means only left OR right have elements left
            //see if left has stuff
        }else if(indexL < left.length){
            result[indexResult] = left[indexL];
            indexL++;
            indexResult++;
        }else if(indexR < right.length){
            result[indexResult] = right[indexR];
            indexR++;
            indexResult++;
        }
    }
    return result;
}

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2015-10-31
    • 2016-06-18
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多