个人记录-LeetCode 74. Search a 2D Matrix

来源:互联网 发布:绿地控股历史价格数据 编辑:程序博客网 时间:2024/06/03 22:43

问题:
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,找到合适的行;
然后对该行进行二分法查找即可,主要是注意细节吧。

代码示例:

public class Solution {    public boolean searchMatrix(int[][] matrix, int target) {        if (matrix == null || matrix.length < 1 || matrix[0].length < 1) {            return false;        }        int rowNum = matrix.length;        int targetLine = -1;        for (int i = 0; i < rowNum; ++i) {            //比较第一列,相等则直接返回            if (matrix[i][0] == target) {                return true;            //否则找到大于target的行            } else if (matrix[i][0] > target) {                targetLine = i;                break;            }        }        int colNum = matrix[0].length;        //没有找到大于target的行        if (targetLine == -1) {            //判断最后一个数是否大于等于target            if (matrix[rowNum-1][colNum-1] == target) {                return true;            } else if (matrix[rowNum-1][colNum-1] > target) {                return middleSearch(matrix[rowNum-1], target);            } else {                //最后一个数都小于target,return false                return false;            }        } else if (targetLine >= 1){            return middleSearch(matrix[targetLine-1], target);        } else {            //第一个数都大于target,return false            return false;        }    }    //其它的情况,二分法即可    private boolean middleSearch(int[] matrix, int target) {        int begin = 0;        int end = matrix.length - 1;        while (begin <= end) {            int middle = (begin + end) / 2;            if (matrix[middle] == target) {                return true;            } else {                if (matrix[middle] > target) {                    end = middle - 1;                } else {                    begin = middle + 1;                }            }        }        return false;    }}
0 0