合并两个排序的ArrayList到一个ArrayList中排序 [英] Merging two sorted Arraylists into one sorted Arraylist

查看:277
本文介绍了合并两个排序的ArrayList到一个ArrayList中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code应该合并两个已经排序的ArrayList到一个排序的ArrayList和如果不将分类用的ArrayList之一,它应该返回null。

My code should merge two already sorted arraylists into one sorted arraylist and if one of the arraylists used is not sorted then it should return null.

public class MergeSorted {
public static void merge(ArrayList<Integer> a, ArrayList<Integer> b) {

    for (int i = 0, j = 0; j < b.size(); i++) {
        if (i == a.size() || a.get(i) > a.get(j)) {
            a.add(i, b.get(j++));
        }
    }
}  
}

这是我尝试,但不能得到返回null的想法,如果他们不相等,进出口新的Java和这是我的第二个星期,所以请耐心和我在一起。我知道我应该有一个if语句检查,如果它们进行排序和其他人,但我应该包括在里面,如果?

This is what I attempted but can't get the idea of returning null if they are not equal, Im new to java and this is my second week so please be patient with me. I know I should have an if statement checking if they are sorted and an else but what should I include inside the if?

推荐答案

问题

检查两个列表进行排序,如果它们是那么它将两个列表合并为一个单一的排序列表,而如果列表不排序返回空

Check if the two lists are sorted, if they are then it will merge the two lists into a single sorted list, whereas if the lists are not sorted return null.

code解决方案:

请尝试以下code:

public class MergeSorted {
public static List merge(List<Integer> aList, List<Integer> bList) {

    List mergeList = new ArrayList<Integer>();

    //checking if list 'A' is sorted
    List temp = new ArrayList(aList);
    Collections.sort(temp);
    boolean aSorted = temp.equals(aList);

    //checking if list 'B' is sorted
    temp = new ArrayList(bList);
    Collections.sort(temp);
    boolean bSorted = temp.equals(bList);

    //if both lists are sorted then merge them
    if(true == aSorted && true == bSorted) {
        mergeList.addAll(aList);
        mergeList.addAll(bList);
        Collections.sort(mergeList);
    }

   return mergeList; 
    }
  }

这篇关于合并两个排序的ArrayList到一个ArrayList中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆