二维数组中的查找

在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

代码格式要求:

public class Solution {
    public boolean Find(int target, int [][] array) {
        
    }
}

解题思路一:

最简单直接当然就是双重循环遍历了,但是这样的话,复杂度就变成了O(m*n),并且题目的条件完全没有用到。

public boolean Find(int target, int [][] array) {
        if(array.length == 0){
            return false;
        }
        for(int[] row : array){
            for(int value : row){
                if(value == target) {
                    return true;
                }
            }
        }
        return false;
    }

解题思路二:

整个二维数组可以看成是一个有序的矩阵,我们从左下角开始遍历,不断利用有序性缩小矩阵的范围,就可以找到了。

举个例子:

1      3      5     7     9

2     4      6      8     10

4     9     12    14    16 

比如说我们现在要找8这个数

8 > 4   ,  元素右移 (此时我们可以知道4上面的元素都不是我们要找的),矩阵就变成了这样。

    3      5     7     9

   4      6      8     10

   9     12    14    16 

8  <  9    元素上移 (9后面的元素全部都不再搜索范围内了),矩阵再次变换。

1      3      5     7      9

    4      6      8     10

4     9     12    14    16 

就这样不断缩小整个矩阵的范围我们就可以找到相应的元素了,当然也有可能找不到,需要自己设置边界条件

完整代码如下:

public class Solution {
    public boolean Find(int target, int [][] array) {
        if(array.length == 0){
            return false;
        }
        int rowLength = array.length;   //总行数
        int columnsLength = array[0].length;   //总列数
        
        int curRow = rowLength - 1; //当前行,初始值为最后一行
        int curColumns = 0;  //当前列
        
        while(curRow >= 0 && curColumns < columnsLength) {
            if(target == array[curRow][curColumns]) { return true;}
            else if( target > array[curRow][curColumns]) {
                curColumns ++;  //右移
            } else{
                curRow --;  //上移
            }
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/bax-life/p/9852705.html