码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Search a 2D Matrix

时间:2015-11-03 00:27:30      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:(链接)

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 first = 0;
 5         int last = matrix.size() - 1;
 6         int len = matrix[0].size();
 7         while (first <= last) {
 8             int mid = first + (last - first) / 2;
 9             if (matrix[mid][0] <= target && target <= matrix[mid][len - 1] ) {
10                 return binarySearch(matrix[mid], target);
11             } else if (matrix[mid][0] > target) {
12                 last = mid - 1;
13             } else if (matrix[mid][len - 1] < target) {
14                 first = mid + 1;
15             }
16         }
17         
18         return false;
19     }
20 
21 private:
22     bool binarySearch(vector<int>& vec, int target) {
23         int first = 0;
24         int last = vec.size() - 1;
25         while (first <= last) {
26             int mid= first + (last -first) / 2;
27             if (vec[mid] == target) {
28                 return true;
29             } else if (vec[mid] < target) {
30                 first = mid + 1;
31             } else {
32                 last = mid - 1;
33             }
34         }
35         
36         return false;
37     }
38 };

 

[LeetCode]Search a 2D Matrix

标签:

原文地址:http://www.cnblogs.com/skycore/p/4931926.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!