Skip to content

Latest commit

 

History

History

2848

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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 with any part of a car.

 

Example 1:

Input: nums = [[3,6],[1,5],[4,7]]
Output: 7
Explanation: All the points from 1 to 7 intersect at least one car, therefore the answer would be 7.

Example 2:

Input: nums = [[1,3],[5,8]]
Output: 7
Explanation: 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.

 

Constraints:

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

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/points-that-intersect-with-cars
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
    int numberOfPoints(vector<vector<int>>& A) {
        sort(begin(A), end(A));
        int start = INT_MIN, end = INT_MIN, ans = 0;
        for (auto &c : A) {
            if (c[0] <= end) {
                end = max(end, c[1]);
            } else {
                if (end != INT_MIN) ans += end - start + 1;
                start = c[0];
                end = c[1];
            }
        }
        return ans + end - start + 1;
    }
};

Solution 2. Difference Array

// OJ: https://leetcode.com/problems/points-that-intersect-with-cars
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(D) where D is the range of A[i]
class Solution {
public:
    int numberOfPoints(vector<vector<int>>& A) {
        int diff[102] = {}, ans = 0;
        for (auto &c : A) {
            diff[c[0]]++;
            diff[c[1] + 1]--;
        }
        for (int i = 1, d = 0; i <= 100; ++i) {
            d += diff[i];
            ans += d > 0;
        }
        return ans;
    }
};