矩阵-搜索二维矩阵II

时间:2025-02-25 07:03:25

搜索二维矩阵II

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。

输入:二维数组,整型变量
输出:布尔值
思路:暴力搜索,使用二分查找

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        //暴力搜索
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                if(matrix[i][j] == target){
                    return true;
                }
            }
        }
        return false;
    }
}

二分查找

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
    //使用二分查找
    for(int[] row : matrix){
        int index = search(row, target);
        if(index >= 0){
            return true;
        }
    }
        return false;
    }
    public int search(int[] nums,int target){
        int low = 0, high = nums.length - 1;
        while(low <= high){
            int mid = (high + low) / 2;
            int num = nums[mid];
            if(num == target){
                return mid;
            }else if(num > target){
                high = mid - 1;
            }else{
                low = mid + 1;
            }
        }
        return -1;
    }
}