###### [Leetcode]Search a 2D Matrix II

Search a 2D Matrix II My Submissions Question
Total Accepted: 19946 Total Submissions: 64757 Difficulty: Medium
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
For example,

Consider the following matrix:

[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.

Given target = 20, return false.

Subscribe to see which companies asked this question

class Solution {
public:
bool search(vector<vector<int>> &matrix,int si,int ei,int sj,int ej,int target){

if(si>ei || sj>ej || matrix[si][sj] > target || matrix[ei][ej] < target)  return false;
//si is up side,ei is down side,sj is left side, ej is right side
int mi = (si + ei) / 2;
int mj = (sj + ej) / 2;

if(matrix[mi][mj] == target)
return true;
else if(matrix[mi][mj] < target){
return search(matrix,si,mi,mj+1,ej,target) ||search(matrix,mi+1,ei,sj,mj,target)||search(matrix,mi+1,ei,mj+1,ej,target);
}
else{
return search(matrix,si,mi-1,mj,ej,target) ||search(matrix,mi,ei,sj,mj-1,target) ||search(matrix,si,mi-1,sj,mj-1,target);
}
}
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty()) return false;

return search(matrix,0,matrix.size()-1,0,matrix[0].size()-1,target);
}
};

 bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
int i = 0, j = n - 1;

// search target from up-right side to down-left side
while (i <= m-1 && j >= 0) {
if (matrix[i][j] == target)
return true;
else if (matrix[i][j] > target)
--j;
else // matrix[i][j] < target
++i;
}

return false;
}

#### leetcode 240: Search a 2D Matrix II

2015-07-23 06:07:35

#### Leetcode 240 Search a 2D Matrix II （二分法和分治法解决有序二维数组查找）

2015-07-23 20:41:07

#### LeetCode 240： Search a 2D Matrix II

2015-07-30 19:07:55

#### Search a 2D Matrix -- LeetCode

2014-04-21 02:29:21

#### LeetCode | Search a 2D Matrix

2013-12-11 11:57:34

#### leetcode解题报告：240. Search a 2D Matrix II

2016-09-12 19:25:51

#### LeetCode74——Search a 2D Matrix

2015-11-14 14:27:29

#### 【LEETCODE】74-Search a 2D Matrix [Python]

2016-01-07 16:04:59

#### LeetCode -- Search a 2D Matrix II

2015-11-21 10:37:35

#### LeetCode 74:Search a 2D Matrix

2016-01-20 21:49:29

## 不良信息举报

[Leetcode]Search a 2D Matrix II