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

 

 

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