0

我需要首先访问然后比较两个单独列表中的元素,并根据具有较小值的元素,删除较小的元素并将其分配到第三个列表中的位置。我该如何做到这一点?

4

2 回答 2

1

我相信您可以将两个列表的元素添加到列表之一的新列表中,然后按升序对其进行排序,例如下面(伪代码):

    List<Integer> list1 = Arrays.asList(2,4,5);
    List<Integer> list2 = Arrays.asList(2,6,8,9,12,56);

    List<Integer> mergedList = new ArrayList<Integer>();
    mergedList.addAll(list1);
    mergedList.addAll(list2);
    Collections.sort(mergedList);

现在mergedList应该有排序的元素。

于 2012-10-07T03:59:31.850 回答
0

仅供您学习,请在下面找到示例手动合并程序

    List<Integer> list1 = Arrays.asList(2,4,5);
    List<Integer> list2 = Arrays.asList(2,6,8,9,12,56);

    List<Integer> mergedList1 = new ArrayList<Integer>();
    mergedList1.add(list1.get(0));

    for(int indx = 1; indx< list1.size(); indx++){
        int valueToMerge = list1.get(indx);
        boolean merged = false;
        for(int indx1 = 0; indx1< mergedList1.size(); indx1++){
            if(mergedList1.get(indx1) > valueToMerge){
                //add the value in middle
                mergedList1.add(indx1, valueToMerge);
                merged = true;
                break;
            }
        }
        if(!merged){
            //add the value in the end
            mergedList1.add(valueToMerge);
        }
    }

    for(int valueToMerge: list2){
        boolean merged = false;
        for(int indx1 = 0; indx1< mergedList1.size(); indx1++){
            if(mergedList1.get(indx1) > valueToMerge){
                //add the value in middle
                mergedList1.add(indx1, valueToMerge);
                merged = true;
                break;
            }
        }
        if(!merged){
            //add the value in the end
            mergedList1.add(valueToMerge);
        }
    }
于 2012-10-07T04:28:40.640 回答