leetcode-剑指Offer-04 |二维数组中的查找

原题

在这里插入图片描述

思路

把二维数组看作n个一维数组,这里的数组是有序的,从小到大,如果大于小的且小于大的,则进行循环比较,这里的循环比较可以进行优化,如果对于较大的数组来讲,可以考虑二分查找。

注意点

二维数组的BUG较多,需要考虑很多前置条件,各种为空,各种=0,这块比较容易错。
这个执行时间真的很迷,第一次提交击败了百分之十,第二次提交击败了百分之百,这是什么鬼。

package leetcode.lcof;


public class Solution_04 {
    
    
    public static void main(String[] args) {
    
    
//        int[][] matrix = {
    
    {1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21
//                , 23, 26, 30}};
        int[][] matrix={
    
    {
    
    -5}};
        System.out.println(findNumberIn2DArray(matrix, -5));
    }

    public static boolean findNumberIn2DArray(int[][] matrix, int target) {
    
    
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
    
    
            return false;
        }
        for (int i = 0; i < matrix.length; i++) {
    
    
            if (matrix[i][0] <= target && matrix[i][matrix[i].length - 1] >= target) {
    
    
                for (int j = 0; j < matrix[i].length; j++) {
    
    
                    if (matrix[i][j] == target) {
    
    
                        return true;
                    }
                }
            }
        }
        return false;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_38173650/article/details/114680309