【问题标题】:merge 2 sorted list with all elements Homework [duplicate]将 2 个排序列表与所有元素合并
【发布时间】:2020-10-23 14:53:31
【问题描述】:

我有一个作业,我已经尝试解决了几个小时。

描述:我们有2个排序数组list,列表a的长度是n,列表b的长度是m;我们假设a和b已经排序,并且列表a和b不包含重复。并且我想如下,但我总是得到一个错误:index out of bound。

public static List<Integer> union(List<Integer> list1, List<Integer> list2 ) {
    List<Integer> union = new ArrayList<>();
    int n1 = 0;
    int n2 = 0;
   

    for (int i = 0; i < list1+list2; i++) {
       ....
}

【问题讨论】:

  • [HINT:] 当列表之一被消耗时会发生什么?
  • 您的问题在于当您到达一个数组的末尾并且在增加比较索引后仍试图获取一个值时。那时您将超出您的数组界限。你需要确保你不会过冲并继续从耗尽的阵列中拉出。

标签: java merge


【解决方案1】:

如果您循环到m + n,其中一个数组的大小可能小于另一个数组,因此数组索引超出范围。相反,您可以使用while 循环,它只会循环到两个列表的最小大小,然后再循环,因为列表已排序,您可以将两个列表中较大的所有剩余元素添加到union

// iterate till the minimum of two lists

while(index1 < a.size() && index2 < b.size()) {
  if (a.get( index1 ) > b.get( index2 )) {
    union.add(i++, b.get( index2++ ));
  }
  else {
    union.add(i++, a.get( index1++ ));
  }
}

//add the elements of the bigger list to the union

while(index1 < a.size()) {
  union.add(i++ ,a.get( index1++ ));
}

while(index2 < b.size()){
  union.add(i++, b.get( index2++ ));
}

【讨论】:

    【解决方案2】:
    public static List<Integer> union(List<Integer> one, List<Integer> two) {
        List<Integer> res = new ArrayList<>(one.size() + two.size());
    
        for (int i = 0, a1 = 0, a2 = 0; i < one.size() + two.size(); i++) {
            if (a1 == one.size())
                res.add(two.get(a2++));
            else if (a2 == two.size())
                res.add(one.get(a1++));
            else
                res.add(one.get(a1) <= two.get(a2) ? one.get(a1++) : two.get(a2++));
        }
    
        return res;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-17
      • 2021-06-15
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多