字符串算法——二維有序數組中查找目標值(Search a 2D Matrix)

問題:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.
思路一:該二維數組是一個有序數組,每一行從左往右遞增,每一列從上往下遞增,最簡單的方法是每個元素都與目標值比較,該方法時間複雜度較高。
思路二:利用數組有序的先驗知識,從數組的左下角[i,j]入手,如果目標值小於該值,則目標值不在該行,與上一行的左下角比較,如果大於該值,則在該行,將該行的元素與之比較。

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix.length<=0 || matrix[0].length<=0){
            return false;
        }
        int row = matrix.length;//行數
        int col = matrix[0].length;//列數
        //從左下角開始查找
        for(int j = 0;j<col;j++){
            for(int i =row-1;i>=0;i--){
                if(matrix[i][j]==target)return true;
                if(matrix[i][j]<target){
                    break;
                }
            }
        }
        return false;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章