首页 > 其他 > 详细

Search a 2D Matrix

时间:2014-02-08 09:19:32      阅读:325      评论: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.
[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

bubuko.com,布布扣
 1 public class Solution {
 2     public boolean searchMatrix(int[][] matrix, int target) {
 3         int len =matrix.length;
 4         if(len<=0) return false;
 5         int len2 = matrix[0].length;
 6         if(len2==0) return false;
 7         if(target<matrix[0][0]) return false;// don‘t forget this!!!
 8         int start = 0, end =len-1;
 9         while(start<=end){
10             int mid = (start+end)/2;
11             if(matrix[mid][0]==target) return true;
12             if(matrix[mid][0]>target){
13                 end = mid-1;
14             }
15             else if(matrix[mid][0]<target){
16                 start = mid+1;
17             }
18         }
19         int row = end;// because target should be greater than target row
20         start = 0;
21         end = len2-1;
22         while(start<=end){
23             int mid = (start+end)/2;
24             if(matrix[row][mid]==target) return true;
25             else if(matrix[row][mid]<target) start = mid+1;
26             else end = mid-1;
27         }
28         return false;
29     }
30 }
View Code

Search a 2D Matrix

原文:http://www.cnblogs.com/krunning/p/3540026.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!