1. 程式人生 > 實用技巧 >劍指 Offer 04. 二維陣列中的查詢 (思維)

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