LeetCode OJ-74.Search a 2D Matrix
題目描述
Write an efficient algorithm that searches for a value in an m x n 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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target =
3
, returntrue
.Subscribe to see which companies asked this question
題目理解
在一個二維矩陣中,求解target是否存在。可以將二維轉化爲一維,在一維數組中去尋找。時間複雜度爲O(m * n),空間複雜度爲O(1)。具體代碼如下:
Code
bool search_matrix(vector<vector<int>> &matrix, int target)
{
int row = (int) matrix.size();
int col = (row > 0) ? (int) matrix[0].size() : 0; //判斷是否是空vector
int sz = row * col;
int i;
for (i = 0; i < sz; ++i) {
if (matrix[i / col][i % col] == target) { //將二維轉化爲一維
return true;
}
}
return false;
}