74. Search a 2D Matrix

来源:互联网 发布:java excel预览 编辑:程序博客网 时间:2024/06/10 22:25

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.

题意:在一个递增的二维数组里查找目标值。

思路:二分查找。先查找所在行,再查找所在列。

class Solution {public:bool searchMatrix(vector<vector<int>>& matrix, int target) {if (matrix.empty())return false;const int LINE = matrix.size();const int COLUMN = matrix[0].size();int low = 0;int high = matrix.size()-1;int mid;while (low <= high){mid = (low + high) / 2;int tmp = matrix[mid][0];if (tmp == target){return true;}else if(tmp > target){high = mid - 1;}else{if (mid + 1 < LINE && matrix[mid + 1][0] <= target){low = mid + 1;}else{break;}}}low = 0;high = COLUMN - 1;while (low <= high){int middle = (low + high) / 2;int tmp = matrix[mid][middle];if (tmp == target)return true;else if (matrix[mid][middle] > target){high = middle - 1;}else{low = middle + 1;}}return false;}};






0 0