首页 > 其他 > 详细

Search a 2D Matrix II

时间:2016-03-19 08:45:22      阅读:223      评论:0      收藏:0      [点我收藏+]

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.

思路:观察矩阵的特点可知,对于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 }

 

Search a 2D Matrix II

原文:http://www.cnblogs.com/FLAGyuri/p/5294271.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!