Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
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
.
思路:观察矩阵的特点可知,对于matrix[i][j]如果大于target那么target一定在从x = i - 1 到 x = 0, y = j 到 y = maxtrix[0].length - 1 范围中,因为matrix[i][j] 必定大于 matrix[x < i][j]的元素。
因此可以考虑从矩阵的bottom left 到 top right 的方向寻找。
1 public class Solution { 2 public boolean searchMatrix(int[][] matrix, int target) { 3 if (matrix == null || matrix.length == 0) { 4 return false; 5 } 6 if (matrix[0] == null || matrix[0].length ==0) { 7 return false; 8 } 9 int x = matrix.length - 1; 10 int n = matrix[0].length; 11 int y = 0; 12 while (x >= 0 && y < n) { 13 if (matrix[x][y] > target) { 14 --x; 15 } else if (matrix[x][y] < target) { 16 ++y; 17 } else { 18 return true; 19 } 20 } 21 return false; 22 } 23 }
原文:http://www.cnblogs.com/FLAGyuri/p/5294271.html