剑指 Offer 04. 二维数组中的查找 (思维)

剑指 Offer 04. 二维数组中的查找

题目链接

  • 本题的解法是从矩阵的右上角开始寻找目标值。
  • 根据矩阵的元素分布特性, 当目标值大于当前位置的值时将row行号++,因为此时目标值一定位于当前行的下面。
  • 当目标值小于当前位置的值时将col列号--,因为此时目标值一定位于当前列的前面。
  • 最后需要注意的一点就是退出while循环的条件(行号大于行数,列号小于0)。
package com.walegarrett.offer;

/**
 * @Author WaleGarrett
 * @Date 2020/12/6 17:15
 */
/*[
    [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]
]*/

public class Offer_04 {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        int n = matrix.length;
        if(n == 0)
            return false;
        int m = matrix[0].length;
        int x = 0;
        int y = m - 1;
        while(true){
            if(x>=n || y<0){
                return false;
            }
            int now = matrix[x][y];
            if(target == now){
                return true;
            }else if(target>now){
                x++;
            }else{
                y--;
            }
        }
    }
}

posted @ 2020-12-06 18:45  Garrett_Wale  阅读(60)  评论(0编辑  收藏  举报