GarrettWale

剑指 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--;
            }
        }
    }
}

分类:

技术点:

相关文章:

  • 2021-06-17
  • 2021-12-09
  • 2021-11-28
  • 2021-05-15
  • 2021-11-29
  • 2021-11-07
  • 2022-02-10
猜你喜欢
  • 2021-06-12
  • 2021-11-18
  • 2021-08-05
  • 2022-01-11
  • 2021-06-06
相关资源
相似解决方案