diff --git a/cpp/2203/220330.cpp b/cpp/2203/220330.cpp new file mode 100644 index 0000000..4dacf7f --- /dev/null +++ b/cpp/2203/220330.cpp @@ -0,0 +1,22 @@ +#include +#include + +/** + * 74. Search a 2D Matrix + * Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: + * - Integers in each row are sorted from left to right. + * - The first integer of each row is greater than the last integer of the previous row. + */ + +class Solution { +public: + static bool searchMatrix(const std::vector>& matrix, int target) { + auto it = std::upper_bound(matrix.begin(), matrix.end(), std::vector{target}, [](const std::vector& x, const std::vector& y) { + return x.front() < y.front(); + }); + if (it == matrix.begin()) + return false; + it = std::prev(it); + return std::binary_search(it->begin(), it->end(), target); + } +}; diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index 71d7eb1..466828c 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220329-CN.cpp) +ADD_EXECUTABLE(2203 220330.cpp)