• 【LeetCode热题100】--240.搜索二维矩阵II


    240.搜索二维矩阵II

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

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

    image-20230925110609460

    方法一:使用二分查找

    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 + low;
                int num = nums[mid];
                if(num == target){
                    return mid;
                }else if(num > target){
                    high = mid -1;
                }else{
                    low = mid + 1;
                }
            }
            return -1;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    方法二:Z字形查找

    从矩阵的右上角(0,n-1)进行搜索,在每一步的搜索过程中,如果我们位于位置(x,y),那么就希望在矩阵的左下角为左下角,以(x,y)为右上角的矩阵中进行搜索,即行的范围为[x,m-1],列的范围为[0,y]

    • 如果 m a t r i x [ x , y ] = t a r g e t matrix[x,y]=target matrix[x,y]=target,说明搜索完成
    • 如果 m a t r i x [ x , y ] > t a r g e t matrix[x,y]>target matrix[x,y]>target,由于每一列的元素都是升序排列的,那么在当前的搜索矩阵中,所有位于第y列的元素都是严格大于target的,因此将其全部忽略,即将y-1
    • 如果 m a t r i x [ x , y ] < t a r g e t matrix[x,y]matrix[x,y]<target,由于每一行的元素都是升序排列的,那么在当前的搜索矩阵中,所有位于第x行的元素都是严格小于target的,因此可以将其全部忽略,即x+1
    class Solution {
        public boolean searchMatrix(int[][] matrix, int target) {
            int m = matrix.length,n = matrix[0].length;
            int x = 0,y = n-1;
            while(x < m && y >= 0){
                if(matrix[x][y] == target){
                    return true;
                }
                if(matrix[x][y] > target){
                    --y;
                }else{
                    ++x;
                }
            }
            return false;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    在Vue中实现可编辑的表格
    java基础10题
    Spring Framework 远程命令执行漏洞CVE-2022-22965
    深度学习入门(二十六)卷积神经网络——池化层
    数据处理包括哪些内容
    【vue网站优化】网页渲染速度快到极致
    如何测试faiss是否为gpu版本
    win11恢复win10版鼠标右键菜单
    【JS】数据结构之栈
    TypeScript基础
  • 原文地址:https://blog.csdn.net/qq_46656857/article/details/133269613