面试题4:二维数组中的查找

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。

请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

package Chapter2_jichuzhishi;

/**
 * @Title: 二维数组中的查找
 * @Description:
 * @Author: Allen
 */
public class Main01 {
    public static void main(String[] args) {
        int[][] arr = {{1,2,8,9},
                {2,4,9,12},
                {4,7,10,13},
                {6,8,11,15}};
        int num=7;
        int rows=4;
        int cols=4;
        Solution slt = new Solution();
        boolean bool= slt.findNum(arr, num, rows, cols);
        System.out.println(bool);
    }
}

class Solution{
    public boolean findNum(int[][] arr, int num, int rows, int cols){
        int row=0, col=cols-1;
        /*while(num!=arr[row][col]){
            if(num > arr[row][col]){
                row++;
                if(row >= rows){
                    return false;
                }
            }
            if(num < arr[row][col]){
                col--;
                if(col < 0){
                    return false;
                }
            }
        }
        return true;*/
        boolean bool=false;
        /**
         * 把边界条件的判断放到while的判断条件中
         */
        while(row < rows && col >=0){
            if(arr[row][col] == num){
                bool = true;
                break;
            }
            else if(arr[row][col] > num){
                col--;
            }else row++;
        }
        return bool;
    } 
}
原文地址:https://www.cnblogs.com/Allen-win/p/7822229.html