Skip to content

Commit

Permalink
feat(line-sweep): Add 2848
Browse files Browse the repository at this point in the history
See LC for unoptimized std::map implementation
  • Loading branch information
euchangxian committed Dec 18, 2024
1 parent f92f5f1 commit f2a2b77
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions C++/2848-PointsThatIntersectWithCars/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <array>
#include <cstddef>
#include <cstdlib>
#include <vector>

class Solution {
public:
int numberOfPoints(std::vector<std::vector<int>>& nums) {
// nums[i] = [start, end], inclusive.
// Line Sweep.
// Counting the number of points is not straightforward? Since its the
// implicit range from minX to maxX.
// Suppose at each x-coordinate we have the number of cars that cover that
// point.
// The number can only be >= 0.
// If it is 0, then we can conclude that this point until the next point
// has no cars covering (the next point must be the start of another Car)
// Thus, we can maintain the number of points that are NOT covered,
// then take (maxX - minX) which represents the total number of points,
// minus the sum of uncovered points.
//
// Can be further optimized by using a fixed size array of size 102, that
// represent the maximum number of points given by the input constraints,
// 1 <= start, end <= 100.
// That way, we can directly count the number of points with
// intersection > 0

// {coordinate, count}
std::array<int, 102> points{};
for (const auto& num : nums) {
++points[num[0]];
--points[num[1] + 1]; // exclusive end
}

int covered = 0;
int cars = 0;
for (const auto count : points) {
cars += count;

if (cars) {
++covered;
}
}
return covered;
}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,7 @@ Now solving in C++. Like it.
| 2830 | MaximizeTheProfitAsASalesman | [![Go](assets/go.svg)](Go/2830-MaximizeTheProfitAsASalesman/Solution.go) |
| 2832 | MaximalRangeThatEachElementIsMaximumInIt | [![C++](assets/c++.svg)](C++/2832-MaximalRangeThatEachElementIsMaximumInIt/Solution.cpp) |
| 2838 | MaximumCoinsHeroesCanCollect | [![C++](assets/c++.svg)](C++/2838-MaximumCoinsHeroesCanCollect/Solution.cpp) |
| 2848 | PointsThatIntersectWithCars | [![C++](assets/c++.svg)](C++/2848-PointsThatIntersectWithCars/Solution.cpp) |
| 2914 | MinimumNumberOfChangesToMakeBinaryStringBeautiful | [![C++](assets/c++.svg)](C++/2914-MinimumNumberOfChangesToMakeBinaryStringBeautiful/Solution.cpp) |
| 2924 | FindChampionTwo | [![C++](assets/c++.svg)](C++/2924-FindChampionTwo/Solution.cpp) |
| 2931 | MaximumSpendingAfterBuyingItems | [![C++](assets/c++.svg)](C++/2931-MaximumSpendingAfterBuyingItems/Solution.cpp) |
Expand Down

0 comments on commit f2a2b77

Please sign in to comment.