标签:
题目来源:http://www.lintcode.com/zh-cn/problem/search-a-2d-matrix/
可以accept的程序如下:
1 class Solution {
2 public:
3 /**
4 * @param matrix, a list of lists of integers
5 * @param target, an integer
6 * @return a boolean, indicate whether matrix contains target
7 */
8 bool searchMatrix(vector<vector<int> > &matrix, int target) {
9 int n = matrix.size();
10 if (n == 0) {
11 return false;
12 }
13 int m = matrix[0].size();
14 int start = 0, end = n * m - 1;//n行m列
15 while (start + 1 < end) {
16 int mid = start + (end - start) / 2;
17 int row = mid / m;
18 int col = mid % m;
19 //从0开始计数,行和列也从0开始计数,第mid个数,在mid/m行,mid%m列
20 if (matrix[row][col] < target) {
21 start = mid;
22 } else {
23 end = mid;
24 }
25 }
26 if (matrix[start / m][start % m] == target) {
27 return true;
28 }
29 if (matrix[end / m][end % m] == target) {
30 return true;
31 }
32 return false;
33 }
34 };
标签:
原文地址:http://www.cnblogs.com/hslzju/p/5455712.html