LeetCode:2848. 与车的相交点 一次遍历,时间复杂度O(n)

2848. 与车的相交点

today 2848. 与车的相交点

题目描述

给你一个下标从 0 开始的二维整数数组 nums 表示汽车停放在数轴上的坐标。对于任意下标 i ,nums[i] = [starti, endi] ,其中 s t a r t i start_i starti 是第 i 辆车的起点, e n d i end_i endi 是第 i 辆车的终点。

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

示例 1:

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

输出:7

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

示例 2:

示例2:

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

输出:7

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

提示:

  • 1 <= nums.length <= 100
  • nums[i].length == 2
  • 1 <= starti <= endi <= 100

题目解析

题目要求找出任意部分 覆盖的整数点的数目。那么我们可以维护一个数组arr,表示所有整数点,由于1 <= starti <= endi <= 100,我们数组的长度为101,其中arr[i]表示整数点i是否被车覆盖。

遍历nums,对于每辆车,我们将 s t a r t i start_i starti 到 e n d i end_i endi 之间的整数点都标记为true,即arr[starti] = true和arr[endi+1] = true。

最后遍历arr,统计true的个数即可。

复杂度分析:

  • 时间复杂度: O ( n ) O(n) O(n)。
  • 空间复杂度: O ( 1 ) O(1) O(1)。

代码实现

C++版本:

cpp 复制代码
class Solution {
public:
    int numberOfPoints(vector<vector<int>>& nums) {
        int n=nums.size();
        int ans=0;
        vector<bool> arr(101,0);
        for(int i=0;i<n;i++){
            for(int j=nums[i][0];j<=nums[i][1];j++){
                if(!arr[j]){
                    ans++;
                    arr[j]=true;
                }
            }
        }
        return ans;
    }
};

Go版本:

go 复制代码
func numberOfPoints(nums [][]int) int { 
    arr:=make([]bool,101)
    ans:=0
    for i:=range(nums){
        for j:=nums[i][0];j<=nums[i][1];j++{
            if(!arr[j]){
                ans++
                arr[j]=true
            }
        }
    }
    return ans
}

Python版本:

python 复制代码
class Solution(object):
    def numberOfPoints(self, nums):
        n=[False]*101
        l=len(nums)
        ans=0
        for i in range(0,l):
            for j in range(nums[i][0],nums[i][1]+1):
                if not n[j]  :
                    ans+=1
                    n[j]=True
        return ans
相关推荐
不会就选b4 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
西部驯兽师6 小时前
制造企业的信息化选型课题(一)
职场和发展
Cccp.1237 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
天真小巫7 小时前
2026.9.28总结
职场和发展
千里码aicood7 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
我命由我123457 小时前
经纪人的职业定义
经验分享·笔记·学习·职场和发展·求职招聘·职场发展·学习方法
做cv的小昊8 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له8 小时前
World-In-World: World Models in a Closed-Loop World
算法
hqyjzsb10 小时前
法律 Prompt 干货:搭建合同审查提示词要包含哪些要素
开发语言·人工智能·python·职场和发展·数据分析·prompt·业界资讯