剑指offer-问题3

package offer;

public class Test03 {

    /**
     * offer问题3
     * @param matrix
     * @param number
     * @return
     */
    public static boolean find(int[][] matrix,int number){
        if (null == matrix || matrix.length < 1 || matrix[0].length < 1){
            return false;
        }

        //总行
        int rows = matrix.length;
        //总列
        //int cols = matrix[1].length;
        int cols = matrix[0].length;

        //从右上角开始查找
        int row = 0;
        int col = cols -1 ;

        while(row >= 0 && row < rows && col >=0 && col < cols){
            if (matrix[row][col] == number){
                return true;
            }else if(matrix[row][col] > number){
                col--;
            }else{
                row++;
            }
        }

        return false;
    }

    public static void main(String[] args){
        int[][] matrix = {
                {1,2,8,9},
                {2,4,9,12},
                {4,7,10,13},
                {6,8,11,15}
        };

        System.out.println(find(matrix,7));
        System.out.println(find(matrix,5));
        System.out.println(find(matrix,1));
        System.out.println(find(matrix,15));
        System.out.println(find(matrix,0));
        System.out.println(find(matrix,16));
        System.out.println(find(null,16));
    }


}

猜你喜欢

转载自blog.csdn.net/ma451152002/article/details/83118402