LeetCode 2848. Points That Intersect With Cars

You are given a 0-indexed 2D integer array nums representing the coordinates of the cars parking on a number line. For any index i, nums[i] = [starti, endi] where starti is the starting point of the ith car and endi is the ending point of the ith car.

Return the number of integer points on the line that are covered with any part of a car.

Example 1:

Input: nums = [[3,6],[1,5],[4,7]]

Output: 7

Explanation: All the points from 1 to 7 intersect at least one car, therefore the answer would be 7.

Example 2:

Input: nums = [[1,3],[5,8]]

Output: 7

Explanation: Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7.

Constraints:

1 <= nums.length <= 100

nums[i].length == 2

1 <= starti <= endi <= 100


这题给了一个array of intervals,求这些intervals里cover了多少个数字。

第一反应就是拿个set来存放所有的数字,最后return size。非常简单。

复制代码
class Solution {
    public int numberOfPoints(List<List<Integer>> nums) {
        Set<Integer> set = new HashSet<>();
        for (List<Integer> num : nums) {
            for (int i = num.get(0); i <= num.get(1); i++) {
                set.add(i);
            }
        }
        return set.size();
    }
}

然后就是这题也算是和interval相关的,就也可以考虑一下line sweep。按照meeting room2的套路,搞了个数组表示所有的points,开头++,结尾--,结果就踩坑了。因为之前的meeting room是结束时间相当于是exclusive的,但这里如果是[1,3]的话需要同时考虑1、2、3相当于是inclusive的。所以刚开始简单粗暴的以为只要在算sum的时候判断如果当前这个point值为-1的话也可以result++。结果没想到还是漏了一种情况,就是[1,1]的时候这里也算一个,但是point的值为0。所以最后看了答案才发现可以在构造points数组的时候在结束+1的时间点再--就可以解决这个问题了。

复制代码
class Solution {
    public int numberOfPoints(List<List<Integer>> nums) {
        int[] points = new int[101];
        for (List<Integer> num : nums) {
            points[num.get(0) - 1]++;
            points[num.get(1)]--;
        }
        int result = 0;
        int prefixSum = 0;
        for (int point : points) {
            prefixSum += point;
            if (prefixSum > 0) {
                result++;
            }
        }
        return result;
    }
}
相关推荐
踩坑记录2 分钟前
leetcode hot100 41.第一个缺失的正数 hard
leetcode
sonadorje6 分钟前
矩阵方程求解
人工智能·算法·矩阵
飞Link21 分钟前
预训练阶段中的模型自我提升、通用模型蒸馏和数据增强中的数据重构和非LLM驱动的数据增强
算法·重构·数据挖掘
实战项目21 分钟前
K-nearest算法在分类问题中的优化
算法·分类·数据挖掘
学嵌入式的小杨同学22 分钟前
【嵌入式 C 语言实战】手动实现字符串四大核心函数(strcpy/strcat/strlen/strcmp)
c语言·开发语言·前端·javascript·数据结构·数据库·算法
qunaa010126 分钟前
基于改进YOLO11-ASF-P2的多旋翼无人机检测识别系统_红外航拍目标检测算法优化_1
算法·目标检测·无人机
Xの哲學29 分钟前
Linux 页回收机制深度剖析: 从设计哲学到实战调试
linux·服务器·网络·算法·边缘计算
幽络源小助理31 分钟前
Yolo-Seg实例分割自动标注工具-幽络源原创
算法·yolo·实例分割·自动标注
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——LeetCode 703 题:数据流中的第 K 大元素
网络·算法·结构与算法
信奥卷王1 小时前
2025年9月GESPC++四级真题解析(含视频)
数据结构·c++·算法