You are given a 0-indexed 2D integer array nums representing the coordinates of the cars parking on a number line. For any index i, nums[i] = [starti, endi] where starti is the starting point of the ith car and endi is the ending point of the ith car.
Return the number of integer points on the line that are covered withany part of a car.
Input: nums =[[1,3],[5,8]]Output: 7Explanation: Points intersecting at least one car are 1,2,3,5,6,7,8. There are a total of 7 points, therefore the answer would be 7.
We need to count all unique integer points that are covered by at least one car’s interval. Since the intervals may overlap, we must avoid double-counting points. For each interval represented by start and end, we can mark every integer point i in that range as covered using a set or boolean array covered.
We can use a set covered to collect all integer points covered by any car. For each interval [start, end], add all integers from start to end (inclusive) to covered. The answer is the size of covered.
Alternatively, we can use a boolean array covered of size 101 (since end ≤ 100) to mark covered points, then count the number of True entries.
import java.util.*;
classSolution {
publicintnumberOfPoints(int[][] nums) {
Set<Integer> covered =new HashSet<>();
for (int[] car : nums) {
for (int i = car[0]; i <= car[1]; i++) {
covered.add(i);
}
}
return covered.size();
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funnumberOfPoints(nums: Array<IntArray>): Int {
val covered = mutableSetOf<Int>()
for (car in nums) {
for (i in car[0]..car[1]) {
covered.add(i)
}
}
return covered.size
}
}
1
2
3
4
5
6
classSolution:
defnumberOfPoints(self, nums: list[list[int]]) -> int:
covered = set()
for start, end in nums:
covered.update(range(start, end +1))
return len(covered)
1
2
3
4
5
6
7
8
9
10
11
12
use std::collections::HashSet;
impl Solution {
pubfnnumber_of_points(nums: Vec<Vec<i32>>) -> i32 {
letmut covered = HashSet::new();
for car in nums.iter() {
for i in car[0]..=car[1] {
covered.insert(i);
}
}
covered.len() asi32 }
}
1
2
3
4
5
6
7
8
9
functionnumberOfPoints(nums: number[][]):number {
constcovered=newSet<number>();
for (const [start, end] ofnums) {
for (leti=start; i<=end; i++) {
covered.add(i);
}
}
returncovered.size;
}