劍指offer 03二維數組的查找(java)

解題思路

  1. 從數組右上角(左下角)開始遍歷;
  2. 當target小於當前值,說明target在當前左邊區域,刪除當前值所在的列;
  3. 大於當前值,說明target在當前值下方,刪除其所在的行;
  4. 等於當前值,直接返回true;
  5. 循壞完畢未找到,返回false;

Java Solution

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        // n次提交代碼心得:matrix爲null 和 matrix行列的長度不一樣。
       // 需要先判斷數組是否爲空,否則可能會出現空指針異常。
        if(matrix != null && matrix.length>0 && matrix[0].length>0){
            int raw = matrix.length;
            int col = matrix[0].length;
            int i = 0;
            int j = col-1;
            while(i<raw && j>=0){
                if(target == matrix[i][j]){
                    return true;
                }
                else if(target < matrix[i][j]){
                    --j;
                }
                else{
                    ++i;
                }
            }
            
        }
        return false;    
    }
}

注意

數組爲空和數組長度爲0的區別

  • null是一個數組類型的空引用。不指向任何對象。對數組進行操作時,需要判斷是否爲空,否者會引起空指針異常。
  • 而長度爲0的數組稱爲“空數組”,空數組是一個對象,只是對象中包含的元素個數爲0。

python Solution

class Solution(object):
    def findNumberIn2DArray(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix != None and len(matrix) > 0 and len(matrix[0]) > 0:
            raws = len(matrix)
            cols = len(matrix[0])
            raw = 0
            col = cols -1
            while raw < raws and col >= 0:
                if matrix[raw][col] == target:
                    return True
                if matrix[raw][col] > target:
                    col -= 1
                else:
                    raw += 1
        return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章