Skip to content

2848. Points That Intersect With Cars 👍

  • Time: $O(n)$
  • Space: $O(100) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int numberOfPoints(vector<vector<int>>& nums) {
    constexpr int kMax = 100;
    int ans = 0;
    int runningSum = 0;
    vector<int> count(kMax + 2);

    for (const vector<int>& num : nums) {
      const int start = num[0];
      const int end = num[1];
      ++count[start];
      --count[end + 1];
    }

    for (int i = 1; i <= kMax; ++i) {
      runningSum += count[i];
      if (runningSum > 0)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int numberOfPoints(List<List<Integer>> nums) {
    final int kMax = 100;
    int ans = 0;
    int runningSum = 0;
    int[] count = new int[kMax + 2];

    for (List<Integer> num : nums) {
      final int start = num.get(0);
      final int end = num.get(1);
      ++count[start];
      --count[end + 1];
    }

    for (int i = 1; i <= kMax; i++) {
      runningSum += count[i];
      if (runningSum > 0)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def numberOfPoints(self, nums: list[list[int]]) -> int:
    kMax = 100
    ans = 0
    runningSum = 0
    count = [0] * (kMax + 2)

    for start, end in nums:
      count[start] += 1
      count[end + 1] -= 1

    for i in range(1, kMax + 1):
      runningSum += count[i]
      if runningSum > 0:
        ans += 1

    return ans