Code & Func
2018-01-27

第96天。

今天的题目是Search a 2D Matrix II:

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
[
2
[1, 4, 7, 11, 15],
3
[2, 5, 8, 12, 19],
4
[3, 6, 9, 16, 22],
5
[10, 13, 14, 17, 24],
6
[18, 21, 23, 26, 30]
7
]

Given target = 5, return true.

Given target = 20, return false.

以前好像看过这道题,但是应该嫌麻烦没做,今天做了一下,感觉好像也不是很难的样子,二分查找的升级版(在2维情况下):

1
bool searchMatrix(vector<vector<int>>& matrix, int target) {
2
int n = matrix.size();
3
if (n == 0) return false;
4
int m = matrix[0].size();
5
return searchMatrix(matrix,0,n-1,0,m-1,target);
6
}
7
8
bool searchMatrix(vector<vector<int> > &matrix, int xlow, int xhigh, int ylow, int yhigh, int target) {
9
10
//cout << xlow << " " << xhigh << endl
11
// << ylow << " " << yhigh << endl;
12
13
if (xlow > xhigh || ylow > yhigh) return false;
14
int xmid = (xlow + xhigh)/2, ymid = (ylow + yhigh)/2;
15
if (matrix[xmid][ymid] == target) return true;
7 collapsed lines
16
else if (matrix[xmid][ymid] < target)
17
return searchMatrix(matrix,xmid + 1, xhigh, ylow, yhigh,target) ||
18
searchMatrix(matrix,xlow, xhigh, ymid + 1, yhigh, target);
19
else
20
return searchMatrix(matrix, xlow, xmid-1, ylow, yhigh,target) ||
21
searchMatrix(matrix,xlow, xhigh, ylow, ymid-1, target);
22
}

为什么dicuss的解法大多都是:

1
bool searchMatrix(vector<vector<int>>& matrix, int target) {
2
int i = 0;
3
int j = matrix[0].size() - 1;
4
5
while(i < matrix.size() && j >= 0) {
6
if(matrix[i][j] == target)
7
return true;
8
9
if(matrix[i][j] < target)
10
i++;
11
else
12
j--;
13
}
14
15
return false;
1 collapsed line
16
}
上一条动态