240. Search a 2D Matrix II

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

 

For example,

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

本题目,开始的时候想法是遍历每一行,每一行使用binary search来做,时间复杂度是O(mlongn)。代码如下:

 1 public class Solution {
 2     public boolean searchMatrix(int[][] matrix, int target) {
 3         if(matrix==null||matrix.length==0||matrix[0].length==0) return false;
 4         int m = matrix.length;
 5         int n = matrix[0].length;
 6         for(int i=0;i<m;i++){
 7             int left = 0,right = n-1;
 8             while(left<=right){
 9                 int mid = left+(right-left)/2;
10                 if(matrix[i][mid]==target) return true;
11                 else if(matrix[i][mid]<target) left = mid+1;
12                 else right = mid-1;
13             }
14         }
15         return false;
16     }
17 }
18 //the run time complexity could be O(mlongn), the space complexity could be O(1);

 

看了答案才知道原来可以达到O(m+n)来做,代码如下:

 1 public class Solution {
 2     public boolean searchMatrix(int[][] matrix, int target) {
 3         if(matrix==null||matrix.length==0||matrix[0].length==0) return false;
 4         int m = matrix.length;
 5         int n = matrix[0].length;
 6         int row = 0;
 7         int col = n-1;
 8         while(row<m&&col>=0){
 9             if(matrix[row][col]==target) return true;
10             else if(matrix[row][col]<target&&row<m-1){
11                 row++;
12             }else if(matrix[row][col]>target&&col>0){
13                 col--;
14             }else{
15                 break;
16             }
17         }
18         return false;
19     }
20 }
21 //the run time complexity would be O(m+n),the space complexity could be O(1);

 

posted @ 2017-03-01 14:17  CodesKiller  阅读(106)  评论(0编辑  收藏  举报