leetcode #74 in cpp

Solution:

We could perform 2 binary searches. The first search is to locate the specific row which potentially contains the target. Once we find the row, we perform binary search in the row to find the target.

Code:

class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
if(target < matrix[0][0] || target > matrix[m-1][n-1]) return false;

<span style="white-space:pre">	</span>int lower_row = 0;
int upper_row = m-1;
int mid_row;
//search for the specific row. The row we are looking for has a range that the target could fall in.
//That is, the target should be larger than the first number and smaller than the last number in the row.
while(lower_row <= upper_row){
mid_row = (lower_row + upper_row) / 2;
if(matrix[mid_row][0] <= target && matrix[mid_row][n-1] >= target){
break;
}
if(matrix[mid_row][n-1] < target ){
lower_row = mid_row + 1;
}
else{
upper_row = mid_row - 1;
}
}
if(lower_row > upper_row) return false;//if lower_row > upper_row, this means the specific row is not found, and thus there are no rows with range the target could fall in. We can termiante now.

int lower_col = 0;
int upper_col = n - 1;
int mid_col;
//binary search through the columns in the row
while(lower_col <= upper_col){
mid_col = (lower_col + upper_col) /2;
if(matrix[mid_row][mid_col] == target) return true;
if(matrix[mid_row][mid_col] < target){
lower_col = mid_col + 1;
}else{
upper_col = mid_col - 1;
}
}
return false;
}
};

LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

[LeetCode74]Pow(x,n)

2014-06-18 04:28:40

LeetCode(74)SearchIn2DMatrix

2014-02-06 03:56:41

LeetCode75——Sort Colors

2015-11-17 20:23:16

免费的LeetCode-cpp题解(C++版本)大全 pdf下载

2018年01月18日 807KB 下载

【leetcode】74. Search a 2D Matrix【java】

2016-12-20 16:56:50

LeetCode 74（Search a 2D Matrix）Java

2016-12-01 09:33:45

【leetcode】第74题 Search a 2D Matrix 题目+解析+JAVA代码

2017-09-11 18:18:15

LeetCode 74:Search a 2D Matrix

2016-01-20 21:49:29

2016-07-21 09:37:42

不良信息举报

leetcode #74 in cpp