搜索二维矩阵

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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

要求在一个二维矩阵找出目标数。这些元素是从左到右递增,从上到下递增。既然排列有规律可循,那么我们不必从头遍历,这样的效率太低了。我们不妨想一下,如果从左往右遍历,当目标数比当前的元素要大时,该怎么样去继续寻找?往右还是往下?

毕竟下面的元素比此元素要大,右面的元素也比此元素要大。所以,如果我们是从左往右遍历时,可能每次都会遇到一个分岔路,处理起来很麻烦。因此我们不妨换一个思路:从数组的右上角开始遍历。如果目标数比当前的元素要大时,它只能位于此元素的下面,此时row+1;如果目标数比当前元素要小时,它必定只能位于此元素的左边,此时col-1。这样一来,即使我们遍历到的元素与目标数不等,也只能有唯一的路可以走,并且可以省去了其他无用的遍历。

实现代码如下:

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

 

posted on 2019-09-14 02:49  Jain_Shaw  阅读(1020)  评论(0编辑  收藏  举报

导航