将数据流变为多个不相交区间

2021-10-08  本文已影响0人  xialu

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/data-stream-as-disjoint-intervals

题目描述:

给你一个由非负整数 a1, a2, ..., an 组成的数据流输入,请你将到目前为止看到的数字总结为不相交的区间列表。
实现 SummaryRanges 类:
SummaryRanges() 使用一个空数据流初始化对象。
void addNum(int val) 向数据流中加入整数 val 。
int[][] getIntervals() 以不相交区间 [starti, endi] 的列表形式返回对数据流中整数的总结。

示例:

输入:
["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]
[[], [1], [], [3], [], [7], [], [2], [], [6], []]
输出:
[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]

解释:

SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = [1]
summaryRanges.getIntervals(); // 返回 [[1, 1]]
summaryRanges.addNum(3); // arr = [1, 3]
summaryRanges.getIntervals(); // 返回 [[1, 1], [3, 3]]
summaryRanges.addNum(7); // arr = [1, 3, 7]
summaryRanges.getIntervals(); // 返回 [[1, 1], [3, 3], [7, 7]]
summaryRanges.addNum(2); // arr = [1, 2, 3, 7]
summaryRanges.getIntervals(); // 返回 [[1, 3], [7, 7]]
summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]
summaryRanges.getIntervals(); // 返回 [[1, 3], [6, 7]]

代码实现:
class SummaryRanges {

    // 记录是否出现过,用boolean数组就可以了
    private boolean[] nums = new boolean[10001];

    public SummaryRanges() {
        
    }
    
    public void addNum(int val) {
        // 出现过标记为true
        nums[val] = true;
    }
    
    public int[][] getIntervals() {
        // 合并区间
        List<int[]> list = new ArrayList<>();
        int start = -1;
        int end = -1;
        for (int i = 0; i < 10001; i++) {
            if (nums[i]) {
                if (start == -1) {
                    start = i;
                    end = i;
                } else {
                    end = i;
                }
            } else {
                if (start != -1) {
                    list.add(new int[] {start, end});
                    start = -1;
                    end = -1;
                }
            }
        }
        // 最后一个元素可能有值
        if (start != -1) {
            list.add(new int[] {start, end});
        }

        // 转换成int[][]返回
        return list.toArray(new int[list.size()][2]);
    }
}

上一篇 下一篇

猜你喜欢

热点阅读