搜索此博客

2013年1月24日星期四

Search a 2D Matrix


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.
Hint: treat it as a one dimensional array, and then perform binary search.

01 public boolean searchMatrix(int[][] matrix, int target) {
02     int m=matrix.length;
03     int n=matrix[0].length;
04     int end=m*n-1;
05     int start=0;
06     while(start<=end)
07     {
08         int mid=(end+start)/2;
09         int row=mid/n;
10         int col=mid%n;
11         if(matrix[row][col]==target)
12         {
13             return true;
14         }
15         else if(matrix[row][col]<target)
16         {
17             start=mid+1;
18         }
19         else
20         {
21             end=mid-1;
22         }
23     }
24     return false;
25 }

没有评论:

发表评论