[LintCode] 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.

4/23/2017

算法班

corner case想的不够全面,第23-28行是后来加上去的,原因是如果target在最后一行或者比任何一个值都大,我们是需要在end那一行找答案的。其他所有情况都是在start那一行找。

 1 public class Solution {
 2     /**
 3      * @param matrix, a list of lists of integers
 4      * @param target, an integer
 5      * @return a boolean, indicate whether matrix contains target
 6      */
 7     public boolean searchMatrix(int[][] matrix, int target) {
 8         // write your code here
 9         
10         if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
11         boolean ret;
12         int start = 0, end = matrix.length - 1;
13         
14         while (start + 1 < end) {
15             int mid = start + (end - start) / 2;
16             if (matrix[mid][0] == target) return true;
17             if (matrix[mid][0] < target) {
18                 start = mid;
19             } else {
20                 end = mid;
21             }
22         }
23         int row;
24         if (matrix[end][0] < target) {
25             row = end;
26         } else {
27             row = start;
28         }
29         int left = 0, right = matrix[row].length - 1;
30         while (left + 1 < right) {
31             int mid = left + (right - left) / 2;
32             if (matrix[row][mid] == target) return true;
33             if (matrix[row][mid] < target) {
34                 left = mid;
35             } else {
36                 right = mid;
37             }
38         }
39         if (matrix[row][right] == target || matrix[row][left] == target) return true;
40         return false;
41     }
42 }

 

posted @ 2017-04-24 08:27  panini  阅读(173)  评论(0编辑  收藏  举报