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
.
基本思路:
1. 先用折半查找,定位到行。
2. 再用折半查找,定位到列。
这里用到的是二段式,二分法查找, 即循环中,只有2个分支,省掉 判等的分支。
在第一次二分退出循环后,需要判断,待查找值,位于当前行前,或者是前一行。
class Solution { public: bool searchMatrix(vector<vector<int> > &matrix, int target) { if (matrix.empty() || matrix[0].empty()) return false; int low = 0, high = matrix.size()-1; while (low < high) { const int mid = low + (high - low) / 2; if (matrix[mid][0] < target) low = mid + 1; else high = mid; } const int row = low && matrix[low][0] > target ? low - 1: low; low = 0, high = matrix[row].size()-1; while (low < high) { const int mid = low + (high - low) / 2; if (matrix[row][mid] < target) low = mid + 1; else high = mid; } return matrix[row][low] == target; } };
此题可以把二维数组,当成一个一维有序数组进行折半查找。
但需要一个将一维坐标,转换成二维坐标的过程。 将需要额外进/和%的运算。
Search a 2D Matrix -- leetcode
原文地址:http://blog.csdn.net/elton_xiao/article/details/45008787