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

leetcode 74. Search a 2D Matrix

时间:2015-02-25 23:42:55      阅读:133      评论: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.

[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

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