标签:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
[Solution]
把二维数组当做len=m * n的一维有序数组,二分查找。
1 bool searchMatrix(vector<vector<int> > &matrix, int target) 2 { 3 int m, n, i, j; 4 if ((m = matrix.size()) <= 0) 5 return false; 6 n = matrix[0].size(); 7 8 int low = 0, high = m * n - 1, middle = 0; 9 while (low <= high) 10 { 11 middle = (low + high) / 2; 12 j = middle % n; 13 if ((middle + 1) % n == 0) 14 i = (middle + 1) / n - 1; 15 else 16 i = (middle + 1) / n; 17 18 if (target == matrix[i][j]) 19 return true; 20 else if (target < matrix[i][j]) 21 high = middle - 1; 22 else 23 low = middle + 1; 24 } 25 26 return false; 27 }
leetcode 74. Search a 2D Matrix
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4300368.html