MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / matrixSearch

Function matrixSearch

cpp/Binary Search/matrix_search.cpp:3–20  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1#include <vector>
2
3bool matrixSearch(std::vector<std::vector<int>>& matrix, int target) {
4 int m = matrix.size(), n = matrix[0].size();
5 int left = 0, right = m * n - 1;
6 // Perform binary search to find the target.
7 while (left <= right) {
8 int mid = (left + right) / 2;
9 int r = mid / n;
10 int c = mid % n;
11 if (matrix[r][c] == target) {
12 return true;
13 } else if (matrix[r][c] > target) {
14 right = mid - 1;
15 } else {
16 left = mid + 1;
17 }
18 }
19 return false;
20}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected