add: 220330 [cpp]

This commit is contained in:
Lam Haoyin 2022-03-30 14:22:57 +08:00
parent 2ba7f554d7
commit 0285e608fd
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 23 additions and 1 deletions

22
cpp/2203/220330.cpp Normal file
View File

@ -0,0 +1,22 @@
#include <vector>
#include <algorithm>
/**
* 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<std::vector<int>>& matrix, int target) {
auto it = std::upper_bound(matrix.begin(), matrix.end(), std::vector<int>{target}, [](const std::vector<int>& x, const std::vector<int>& 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);
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220329-CN.cpp)
ADD_EXECUTABLE(2203 220330.cpp)