74. Search a 2D Matrix java solutions

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.

 1 public class Solution {
 2     public boolean searchMatrix(int[][] matrix, int target) {
 3         int m = matrix.length, n = matrix[0].length;
 4         if(m == 0 || n == 0) return false;
 5         int i = m-1,j = 0;
 6         while(i >= 0 && j < n){
 7             if(matrix[i][j] == target) return true;
 8             if(matrix[i][j] > target) i--;
 9             else j++;
10         }
11         return false;
12     }
13 }

该题矩阵也是有特点的。 对比题目:

http://www.cnblogs.com/guoguolan/p/5620209.html

解法二: 可以使用二分查找做,不过应该没有利用矩阵的特点来做速度快。

原文地址:https://www.cnblogs.com/guoguolan/p/5622395.html