LeetCode 2848. 与车相交的点

2848. 与车相交的点

给你一个下标从 0 开始的二维整数数组 nums 表示汽车停放在数轴上的坐标。对于任意下标 inums[i] = [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 。

提示:

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

提示 1
Sort the array according to first element and then starting from the 0th index remove the overlapping parts and return the count of non-overlapping points.

解法:差分数组

Java版:
class Solution {
    public int numberOfPoints(List<List<Integer>> nums) {
        int[] diff = new int[101];
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < nums.size(); i++) {
            int start = nums.get(i).get(0);
            int end = nums.get(i).get(1);
            min = Math.min(min, start);
            max = Math.max(max, end);
            diff[start] += 1;
            if (end + 1 <= 100) {
                diff[end + 1] -= 1;
            }
        }
        int ans = 0;
        int presum = 0;
        for (int i = min; i <= max; i++) {
            presum += diff[i];
            if (presum > 0) {
                ans++;
            }
        }
        return ans;
    }
}
Python3版:
 
class Solution:
    def numberOfPoints(self, nums: List[List[int]]) -> int:
        diff = [0] * 101
        minv = inf
        maxv = -inf 
        for start, end in nums:
            minv = min(minv, start)
            maxv = max(maxv, end)
            diff[start] += 1
            if end + 1 <= 100:
                diff[end + 1] -= 1

        ans = 0
        presum = 0
        for i in range(minv, maxv + 1):
            presum += diff[i]
            if presum > 0:
                ans += 1
        return ans
复杂度分析
  • 时间复杂度:O(n+max{endi​})。其中 n 为 nums 的长度。
  • 空间复杂度:O(1)。
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值