|
1 | 1 | // Time: O(nlogn)
|
2 | 2 | // Space: O(1)
|
3 | 3 |
|
| 4 | +// Using template. |
4 | 5 | class Solution {
|
5 | 6 | public:
|
6 | 7 | int minArea(vector<vector<char>>& image, int x, int y) {
|
7 | 8 | using namespace std::placeholders; // for _1, _2, _3...
|
8 | 9 |
|
| 10 | + const auto searchColumns = |
| 11 | + [](const vector<vector<char>>& image, bool has_one, const int mid) { |
| 12 | + return has_one == any_of(image.cbegin(), image.cend(), |
| 13 | + [=](const vector<char>& row) { return row[mid] == '1'; }); |
| 14 | + }; |
| 15 | + const auto searchRows = |
| 16 | + [](const vector<vector<char>>& image, bool has_one, const int mid) { |
| 17 | + return has_one == any_of(image[mid].cbegin(), image[mid].cend(), |
| 18 | + [](const char& col) { return col == '1'; }); |
| 19 | + }; |
| 20 | + |
| 21 | + const int left = binarySearch(0, y - 1, bind(searchColumns, image, true, _1)); |
| 22 | + const int right = binarySearch(y + 1, image[0].size() - 1, bind(searchColumns, image, false, _1)); |
| 23 | + const int top = binarySearch(0, x - 1, bind(searchRows, image, true, _1)); |
| 24 | + const int bottom = binarySearch(x + 1, image.size() - 1, bind(searchRows, image, false, _1)); |
| 25 | + |
| 26 | + return (right - left) * (bottom - top); |
| 27 | + } |
| 28 | + |
| 29 | +private: |
| 30 | + template<typename T> |
| 31 | + int binarySearch(int left, int right, const T& find) { |
| 32 | + while (left <= right) { |
| 33 | + const int mid = left + (right - left) / 2; |
| 34 | + if (find(mid)) { |
| 35 | + right = mid - 1; |
| 36 | + } else { |
| 37 | + left = mid + 1; |
| 38 | + } |
| 39 | + } |
| 40 | + return left; |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +// Using std::bind(). |
| 45 | +class Solution2 { |
| 46 | +public: |
| 47 | + int minArea(vector<vector<char>>& image, int x, int y) { |
| 48 | + using namespace std::placeholders; // for _1, _2, _3... |
| 49 | + |
9 | 50 | const auto searchColumns =
|
10 | 51 | [](const vector<vector<char>>& image, bool has_one, const int mid) {
|
11 | 52 | return has_one == any_of(image.cbegin(), image.cend(),
|
@@ -46,8 +87,8 @@ class Solution {
|
46 | 87 | }
|
47 | 88 | };
|
48 | 89 |
|
49 |
| - |
50 |
| -class Solution2 { |
| 90 | +// Using lambda. |
| 91 | +class Solution3 { |
51 | 92 | public:
|
52 | 93 | int minArea(vector<vector<char>>& image, int x, int y) {
|
53 | 94 | const auto searchColumns =
|
|
0 commit comments