Leetcode -- Search a 2D Matrix

来源:互联网 发布:淘宝假面骑士铠武腰带 编辑:程序博客网 时间:2024/05/19 01:31

https://oj.leetcode.com/problems/search-a-2d-matrix/

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.

这一题你可以考虑二分,根据行和列分成四块。

但接下来只介绍一种比较简便的做法,我们一开始就把位置定在右上角,当当前数字比target大,往下走,当前数字比target小,就往左走。这样最后要不就是找到target返回true,要不就是过界返回false。这种做法的理念貌似是和dp有关的。。当然,我还不是特别明白。。也就是,我是背答案的。。谢谢。。囧

    public boolean searchMatrix(int[][] matrix, int target) {        if(matrix.length == 0 || matrix[0].length == 0)            return false;        int right = matrix[0].length - 1;        int top = 0;        while(top < matrix.length && right >= 0){            if(target > matrix[top][right])                top++;            else if(target < matrix[top][right])                right--;            else                return true;        }        return false;    }


0 0