题解 | #合并区间#

合并区间

https://www.nowcoder.com/practice/0596b6232ce74b18b60ba0367d7f2492

import java.util.Scanner;
import java.util.*;
import java.util.stream.Collectors;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            List<IntervalMergeVO> intervalMergeVOList = new ArrayList<>();
            String next = scanner.nextLine();
            String areaArray[] = next.split(" ");

            for (String str : areaArray) {
                String numberArray[] = str.split(",");
                IntervalMergeVO intervalMergeVO = new IntervalMergeVO(Integer.parseInt(
                            numberArray[0]), Integer.parseInt(numberArray[1]));
                intervalMergeVOList.add(intervalMergeVO);
            }

            // 排序
            List<IntervalMergeVO> result = intervalMergeVOList.stream().sorted(
                                               Comparator.comparing(IntervalMergeVO::getX)).collect(Collectors.toList());
            List<IntervalMergeVO> responseList = new ArrayList<>();
            IntervalMergeVO temp = null;
            for (IntervalMergeVO intervalMergeVO : result) {
                // 第一个
                if (temp == null) {
                    temp = intervalMergeVO;
                    responseList.add(temp);
                    continue;
                }
                // 第二个开始
                IntervalMergeVO vo = couldMerge(temp, intervalMergeVO);
                if (vo != null) {
                    // 移除之前的,因为合并了,换成合并的内容
                    responseList.remove(temp);
                    temp = vo;
                    responseList.add(vo);
                } else {
                    temp = intervalMergeVO;
                    responseList.add(temp);
                }

            }

            for (IntervalMergeVO intervalMergeVO : responseList) {
                System.out.print(intervalMergeVO.getX() + "," + intervalMergeVO.getY() + " ");
            }
        }
    }

    /**
     * 判断是否可以合并,如果可以就返回合并,否则返回null
     * <p>
     * 有交集就合并
     *
     * @param o1
     * @param o2
     * @return
     */
    public static IntervalMergeVO couldMerge(IntervalMergeVO o1,
            IntervalMergeVO o2) {
        if (o1.y >= o2.x) {
            int maxX = Math.min(o1.x, o2.x);
            int maxY = Math.max(o1.y, o2.y);
            return new IntervalMergeVO(maxX, maxY);
        }
        return null;
    }
}

class IntervalMergeVO {
    int x;
    int y;

    public IntervalMergeVO(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务