aboutsummaryrefslogtreecommitdiff
path: root/works/solutions/cpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2020-05-11 16:27:17 +0800
committercrupest <crupest@outlook.com>2020-05-11 16:27:17 +0800
commitbd0f87150d82eb4370b8502ff2d2a221e69545a6 (patch)
treeff338bb41b1b4f32965b6e61698f67c40aafeef0 /works/solutions/cpp
parenta3a2519a087f710c8820d94584648aaba75528d7 (diff)
downloadcrupest-bd0f87150d82eb4370b8502ff2d2a221e69545a6.tar.gz
crupest-bd0f87150d82eb4370b8502ff2d2a221e69545a6.tar.bz2
crupest-bd0f87150d82eb4370b8502ff2d2a221e69545a6.zip
import(solutions): Add problem 74.
Diffstat (limited to 'works/solutions/cpp')
-rw-r--r--works/solutions/cpp/74.cpp63
1 files changed, 63 insertions, 0 deletions
diff --git a/works/solutions/cpp/74.cpp b/works/solutions/cpp/74.cpp
new file mode 100644
index 0000000..08560ef
--- /dev/null
+++ b/works/solutions/cpp/74.cpp
@@ -0,0 +1,63 @@
+#include <vector>
+
+using std::vector;
+
+class Solution
+{
+public:
+ bool searchMatrix(vector<vector<int>> &matrix, int target)
+ {
+ if (matrix.empty() || matrix.front().empty())
+ return false;
+
+ int top_row = 0;
+ int bottom_row = matrix.size() - 1;
+ while (top_row != bottom_row)
+ {
+ const int middle_row = (top_row + bottom_row) / 2;
+ const int middle_row_p1 = middle_row + 1;
+ const int middle_p1_row_front = matrix[middle_row_p1].front();
+ if (middle_p1_row_front > target)
+ {
+ bottom_row = middle_row;
+ }
+ else if (middle_p1_row_front < target)
+ {
+ top_row = middle_row_p1;
+ }
+ else if (middle_p1_row_front == target)
+ {
+ return true;
+ }
+ }
+
+ const vector<int> &row = matrix[top_row];
+
+ if (row.size() == 1)
+ {
+ return row.front() == target;
+ }
+
+ int left = 0;
+ int right = row.size() - 1;
+
+ while (left != right)
+ {
+ const int middle = (left + right) / 2;
+ const int middle_value = row[middle];
+ if (middle_value == target)
+ {
+ return true;
+ }
+ else if (middle_value < target)
+ {
+ left = middle + 1;
+ }
+ else
+ {
+ right = middle;
+ }
+ }
+ return row[left] == target;
+ }
+};