【数据结构-一维差分】力扣2848. 与车相交的点

给你一个下标从 0 开始的二维整数数组 nums 表示汽车停放在数轴上的坐标。对于任意下标 i,numsi = starti, endi ,其中 starti 是第 i 辆车的起点,endi 是第 i 辆车的终点。

返回数轴上被车 任意部分 覆盖的整数点的数目。

示例 1:

输入:nums = \[3,6,1,5,4,7]

输出:7

解释:从 1 到 7 的所有点都至少与一辆车相交,因此答案为 7 。

示例 2:

输入:nums = \[1,3,5,8]

输出:7

解释:1、2、3、5、6、7、8 共计 7 个点满足至少与一辆车相交,因此答案为 7 。

差分

cpp 复制代码
class Solution {
public:
    int numberOfPoints(vector<vector<int>>& nums) {
        auto it = std::max_element(nums.begin(), nums.end(), [](const auto& a, const auto& b) {
            return a[1] < b[1];
        });
        int max_end = (*it)[1];
        vector<int> dif(max_end+2);

        for(auto& i : nums){
            dif[i[0]]++;
            dif[i[1]+1]--;
        }
        int ans = 0, s = 0;
        for(int d : dif){
            s += d;
            ans += s > 0;
        }
        return ans;
    }
};

传统的暴力方法时间复杂度接近N^2,而差分方法时间复杂度在N。

差分的基础知识https://leetcode.cn/problems/points-that-intersect-with-cars/solutions/2435384/chai-fen-shu-zu-xian-xing-zuo-fa-by-endl-3xpm/

相关推荐
Data analyse45636 分钟前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
Navigator_Z2 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2082 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年3 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.3333 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
jeo陽3 小时前
04-循环实战:素数、最大公约数、级数求和与枚举法
c语言·开发语言·数据结构
Nil2083 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
神工坊3 小时前
技术分享︱SIMFORGE HSF® 网格加密与热点加速技术实践
算法·hpc·网格·cae·工程仿真·数值引擎·samr
Nil2084 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
CV@CV4 小时前
世界模型与智能体协同推理逻辑
人工智能·算法·边缘计算·量子计算·具身智能