You are given an m x n
integer matrix matrix
with the following two properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the previous row.
Given an integer target
, return true
if target
is in matrix
or false
otherwise.
You must write a solution in O(log(m * n))
time complexity.
Example 1:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true
Example 2:
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 Output: false
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
Companies: Amazon, Bloomberg, Yahoo
Related Topics:
Array, Binary Search, Matrix
Similar Questions:
// OJ: https://leetcode.com/problems/search-a-2d-matrix/
// Author: github.com/lzl124631x
// Time: O(log(MN))
// Space: O(1)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& A, int target) {
if (A.empty() || A[0].empty()) return false;
int L = 0, R = A.size() - 1;
while (L <= R) {
int M = (L + R) / 2;
if (A[M][0] == target) return true;
if (A[M][0] < target) L = M + 1;
else R = M - 1;
}
if (R == -1) return false;
int row = R;
L = 0, R = A[0].size() - 1;
while (L <= R) {
int M = (L + R) / 2;
if (A[row][M] == target) return true;
if (A[row][M] < target) L = M + 1;
else R = M - 1;
}
return false;
}
};
L <= R
template:
// OJ: https://leetcode.com/problems/search-a-2d-matrix/
// Author: github.com/lzl124631x
// Time: O(log(MN))
// Space: O(1)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& A, int target) {
int M = A.size(), N = A[0].size(), L = 0, R = M * N - 1;
while (L <= R) {
int mid = (L + R) / 2, x = mid / N, y = mid % N;
if (A[x][y] == target) return true;
if (A[x][y] < target) L = mid + 1;
else R = mid - 1;
}
return false;
}
};
L < R
template:
// OJ: https://leetcode.com/problems/search-a-2d-matrix/
// Author: github.com/lzl124631x
// Time: O(log(MN))
// Space: O(1)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& A, int target) {
int M = A.size(), N = A[0].size(), L = 0, R = M * N - 1;
while (L < R) {
int M = (L + R) / 2, i = M / N, j = M % N;
if (A[i][j] < target) L = M + 1;
else R = M;
}
return A[L / N][L % N] == target;
}
};
// OJ: https://leetcode.com/problems/search-a-2d-matrix/
// Author: github.com/lzl124631x
// Time: O(M + N)
// Space: O(1)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& A, int target) {
if (A.empty() || A[0].empty()) return false;
int M = A.size(), N = A[0].size(), i = 0, j = N - 1;
while (i < M && j >= 0) {
if (A[i][j] == target) return true;
if (A[i][j] < target) ++i;
else --j;
}
return false;
}
};