LeetCode-搜索二维矩阵 II

139 阅读1分钟

算法记录

LeetCode 题目:

  编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。


说明

一、题目

  编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。

二、分析

  • 方向上有序, 只需要在行, 列上进行移动即可.
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int i = 0, j = matrix[0].length - 1;
        while(i <= matrix.length - 1 && j >= 0) {
            if(matrix[i][j] > target) j--;
            else if(matrix[i][j] < target) i++;
            else return true;
        }
        return false;
    }
}

总结

熟悉二分查找。