"Sword Finger Offer" series one-search in a two-dimensional array

The first lesson of "Sword Value Offer"

One question every day, one step forward.

Lookup in a two-dimensional array

Topic :
In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom.
Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.

Ideas :
1. The subject mainly examines the traversal of two-dimensional arrays. What are the common methods for array traversal?
2. The simplest one should be a for loop. This question is solved by a for loop.
3. A two-dimensional array is traversed by two for loops. The outer for takes rows and the inner for takes columns
. 3. Then define a boolean The basic type of the type, the initial value is false
4. Make a judgment, when the data in the array is equal to the integer, the boolean type will be changed to true and return, otherwise, the initial value will be returned directly.
5. Not much to say, just go to the code...

Code :

/*
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,
每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
 */
public class DoubleArrayDemo01 {
    
    
    public boolean Find(int target, int [][] array) {
    
    
        boolean a = false;//定义初始布尔值
        for (int i = 0; i < array.length; i++) {
    
    //外层循环——行
            for (int j = 0;j<array.length;j++){
    
    //内层循环——列
                if(array[i][j]==target)//判断相等
                    a = true;//若相等,赋值为true
            }
        }
        return a;//返回布尔值
    }
}

Conclusion: This question mainly examines the traversal of two-dimensional arrays. There are thousands of methods. I still prefer to use for loop traversal.

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/105231822