Leetcode做題日記:74. 搜索二維矩陣(java)

 

題目:看到矩陣的時候,也許你會虛,我線性代數沒學好可能寫不出來,別怕其實就是二維數組的遍歷而已,認識到這一點,你就成功了一半,Just kidding,代碼實現不了有思路跟沒思路一樣,

最優算法查找方式見圖中紅色的箭頭;

java基礎知識:

獲取二維數組的長度;

獲取行數: int rowLength = array.length;
獲取列數: int colLength = array[0].length;

上代碼:

 

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        
        if(matrix==null||matrix.length==0||matrix[0].length==0){
            return false;
        }
      int row =matrix.length;
      int col = matrix[0].length;
        int c =0 ;
        int l =col-1;
        while(c<row&&l>=0){
            if(target==matrix[c][l]){
                return true;
            }else if(target>matrix[c][l]){
                c++;
            }else{
                l--;
            }
        }
      return false;  
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章