【Java-区间合并】

给定若干连续的有序区间(默认是升序),将有交集的区间合并成一个连续的区间。

举例:

输入:[[1,5],[3,7],[4,8],[10,12],[11,16],[18,20]]

输出:[[1,8],[10,16],[18,20]]

解决代码:

public static void main(String[] args) {

    String a = "[[1,5],[3,7],[4,8],[10,12],[11,16],[18,20]]";

    List list = JSONUtil.toList(JSONUtil.parseArray(a), List.class);

    List returnList = new ArrayList<>();

    List canUpdateList = list.get(0);

    for (int i = 1; i < list.size(); i++) {

        Integer listFirstNum = canUpdateList.get(0);
        Integer listSecNum = canUpdateList.get(1);

        List objectList = list.get(i);

        Integer firstNumA = objectList.get(0);
        Integer secNumA = objectList.get(1);

        if (listFirstNum < firstNumA && listSecNum > firstNumA && listSecNum < secNumA) {
            canUpdateList.set(1, secNumA);
        } else {
            canUpdateList = objectList;
        }


        if (!CollectionUtil.contains(returnList, canUpdateList)) {
            returnList.add(canUpdateList);
        }

        System.out.println("canUpdateList:" + canUpdateList);
        System.out.println("==========");
    }
    System.out.println("returnList:" + returnList);
    
}

你可能感兴趣的:(java,开发语言,后端)