字符串算法——二维有序数组中查找目标值(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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章