题解 | 区间合并-2注意重叠和相邻的区间都要合并,而不是只有重叠

区间合并-2

https://www.nowcoder.com/practice/9be49b2117b44622ae3cef456dbc7e70

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<int[]> nums = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int a = sc.nextInt(), b = sc.nextInt();
            nums.add(new int[] {a, b});
        }
        nums.sort(Comparator.comparingInt((int[] o) -> o[0]).thenComparingInt(
                      o -> o[1]));
        List<int[]> ans = new LinkedList<>();
        int i = 0;
        while (i < n) {
            int left = nums.get(i)[0], right = nums.get(i)[1];
            while (i < n - 1 && right >= nums.get(i + 1)[0] - 1) {
                if (nums.get(i + 1)[1] > right) right = nums.get(i + 1)[1];
                i++;
            }
            ans.add(new int[] {left, right});
            i++;
        }
        ans.forEach(o -> System.out.println(o[0] + " " + o[1]));
        sc.close();
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务