Leetcode 2848. Points That Intersect With Cars
You are given a 0-indexed 2D integer array cars
, where cars[i] = [start_i, end_i]
indicates the starting and ending points of the i-th
car on an infinite number line.
Return the number of integer points on the line that are covered with exactly one car.
Input: cars = [[1, 3], [2, 5], [6, 8]]
Output: 3
Explanation: The cars cover points 1, 2, 3, 4, 5, 6, 7, 8.
Cars covering each point:
1 -> [1, 3]
2 -> [1, 3], [2, 5]
3 -> [1, 3], [2, 5]
4 -> [2, 5]
5 -> [2, 5]
6 -> [6, 8]
7 -> [6, 8]
8 -> [6, 8]
- Points 1, 4, 6 are covered by exactly one car -> return 3.
cars
array be?
#include <vector>
#include <map>
using namespace std;
int countPoints(vector<vector<int>>& cars) {
map<int, int> events;
// Record start and end+1 of each interval in the map
for (auto& car : cars) {
int start = car[0];
int end = car[1] + 1;
events[start]++;
events[end]--;
}
int current_coverage = 0;
int prev_point = 0;
int count = 0;
// Traverse the events in sorted order
for (auto& event : events) {
int point = event.first;
int change = event.second;
if (current_coverage == 1) {
count += point - prev_point;
}
current_coverage += change;
prev_point = point;
}
return count;
}
int main() {
vector<vector<int>> cars = \{\{1, 3}, {2, 5}, {6, 8}};
int result = countPoints(cars);
// Output: 3 (points 1, 4, 6 are covered by exactly one car)
printf("%d", result);
return 0;
}
In the above code:
This method ensures efficient handling of a potentially large input size with intervals.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?