剑指Offer面试题4(Java版):二维数组中的查找

题目描述

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

解题思路一:

暴力求解,代码如下:

public class Solution {
    public boolean Find(int target, int [][] array) {
        for(int[]i:array)
            for(int j:i)
                if(j == target)
                    return true;
        return false;
    }
}

时间复杂度O(N2) 空间复杂度O(1)

解题思路二:

例如输入下列数组

1

2

8

扫描二维码关注公众号,回复: 6186650 查看本文章

9

2

4

9

12

4

7

10

13

6

8

11

15

待查找整数target = 7

首先我们取右上角的9与7进行比较,发现9>7 因为9是第四列最小的一个数,因此证明target不可能出现在第四列,因此比较范围缩小到

1

2

8

2

4

9

4

7

10

6

8

11

再次取右上角8>7 同理target不可能出现在第三列,因此比较范围缩小到

1

2

2

4

4

7

6

8

再次取右上角2>7 因此7有可能出现在该列 ,因此在第二类从上到下依次比较,发现array[3][1] = target,因此查找成功 。

但是如果在该列遇到array[i][1]>target 则说明 该列也不可能出现target,考虑缩减到array[i][0]进行比较

代码如下:

public class Solution {
    public boolean Find(int target, int [][] array) {
        int m = array.length;
        int n = array[0].length;
        if(m == 0 || n == 0)//数组为空
            return false;
        int row = 0;
        int col = n-1;
        while(row<m && col>=0){
            if(array[row][col] == target)
                return true;
            else if(array[row][col] > target)
                col--;
            else
                row++;
        }
        return false;
    }
}


猜你喜欢

转载自blog.csdn.net/qq_25406563/article/details/87646967