From f2a2b77380cb991b98ce0bcdca059e8df0e4a288 Mon Sep 17 00:00:00 2001 From: euchangxian Date: Wed, 18 Dec 2024 14:23:58 +0800 Subject: [PATCH] feat(line-sweep): Add 2848 See LC for unoptimized std::map implementation --- .../Solution.cpp | 46 +++++++++++++++++++ README.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 C++/2848-PointsThatIntersectWithCars/Solution.cpp diff --git a/C++/2848-PointsThatIntersectWithCars/Solution.cpp b/C++/2848-PointsThatIntersectWithCars/Solution.cpp new file mode 100644 index 0000000..3b611cc --- /dev/null +++ b/C++/2848-PointsThatIntersectWithCars/Solution.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include + +class Solution { + public: + int numberOfPoints(std::vector>& 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 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; + } +}; diff --git a/README.md b/README.md index a7730d8..95057bc 100644 --- a/README.md +++ b/README.md @@ -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) |