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

Search a 2D Matrix

时间:2015-07-16 18:38:36      阅读:83      评论: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.

 

解题思路:利用两次二分查找法。因为所给矩阵第一列也是升序排列的,所以可以先对第一列进行二分查找,锁定该元素所在行数,然后再对列进行二分查找,即可判断target是否存在。这个的算法时间复杂度是O(log(rows)+log(columns))。 

 

代码

 1 public class Solution {
 2     public boolean searchMatrix(int[][] matrix, int target) 
 3     {
 4         if(matrix.length==0||matrix[0].length==0||matrix==null) return false;
 5         
 6         int low=0;
 7         int high=matrix.length-1;
 8         
 9         while(low<=high)
10         {
11             int mid=(high+low)/2;
12             if(target>matrix[mid][0])
13             {
14                 low=mid+1;
15             }
16             else if (target<matrix[mid][0])
17             {
18                 high=mid-1;
19             }
20             else return true;
21         }
22         
23         int row=high; //当从while中跳出时,low指向的值肯定比target大,而high指向的值肯定比target小
24         
25         if(row<0) return false; 
26         
27         low=0;
28         high=matrix[0].length-1;
29         while(low<=high)
30         {
31             int mid=(high+low)/2;
32             if(target>matrix[row][mid])
33             {
34                 low=mid+1;
35             }
36             else if (target<matrix[row][mid])
37             {
38                 high=mid-1;
39             }
40             else return true;
41         }
42         
43         return false;
44     }
45 }

 

reference: http://blog.csdn.net/linhuanmars/article/details/24216235

http://www.cnblogs.com/springfor/p/3857959.html

Search a 2D Matrix

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4651751.html

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