LeetCode OJ: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
, return true
.
二分法的简单变形,把整个数组当成一个长的大数组就可以了,代码如下:
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 int szHor = matrix.size(); 5 if(!szHor) return false; 6 int szVer = matrix[0].size(); 7 if(!szVer) return false; 8 int totalSize = szHor * szVer; 9 return bs(matrix, 0, totalSize - 1, target, szVer); 10 11 } 12 13 bool bs(vector<vector<int>> & matrix, int beg, int end, int target, int colCount) 14 { 15 if(beg > end) 16 return false; 17 int mid = beg + (end - beg)/2; 18 int val = matrix[mid/colCount][mid%colCount]; 19 if(val == target) return true; 20 else if(val < target) 21 return bs(matrix, mid + 1, end, target, colCount); 22 else 23 return bs(matrix, beg, mid - 1, target, colCount); 24 } 25 26 27 };