java 在有序矩阵中搜索

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 在有序矩阵中搜索相关的知识,希望对你有一定的参考价值。

/*
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
*/

 public boolean searchMatrix(int[][] matrix, int target) {
        
        //ERROR CHECK:
        
        //Matrix empty
            if(matrix.length == 0 || matrix[0].length == 0) return false;
        //Target not in matrix
            int rows = matrix.length;
            int columns = matrix[0].length;
            if(target < matrix[0][0] || target > matrix[rows-1][columns-1]) return false;
        
        int row = rows-1;
        int column = 0;
        
        while(row >= 0 && column < columns){
            if(matrix[row][column] == target) return true;
            else if(matrix[row][column] > target) row--;
            else column ++;
        }
        
        return false;    
    
    }
    
    
/*
 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.
*/

 public boolean searchMatrix(int[][] matrix, int target) {
     
        if(matrix.length == 0 || matrix[0].length == 0) return false;
        
        int row = 0;
       
        while(row < matrix.length && matrix[row][0] <= target){
            if(matrix[row][0] == target) return true;
            row++;
        }
        
        if(row == 0) return false;
        
        if(Arrays.binarySearch(matrix[row-1], target) >= 0) return true;
        else return false;
        
    }

以上是关于java 在有序矩阵中搜索的主要内容,如果未能解决你的问题,请参考以下文章

python 有序矩阵搜索

leetcode.矩阵.378有序矩阵中第K小的元素-Java

LeetCode 378. 有序矩阵中第K小的元素 Java

二维数组3:搜索二维矩阵

LeetCode74. 搜索二维矩阵

有序数组中的线性搜索 - Java