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

[LintCode] Search a 2D Matrix

时间:2017-04-24 10:09:42      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:write   target   class   arc   from   lis   log   mat   previous   

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 }

 

[LintCode] Search a 2D Matrix

标签:write   target   class   arc   from   lis   log   mat   previous   

原文地址:http://www.cnblogs.com/panini/p/6755064.html

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