zoukankan      html  css  js  c++  java
  • 二维数组中查找 3

    先判断数组是否为空,为空返回false

       

    不为空进入循环

       

    获得矩阵的行数:rows=matrix.length

    获得矩阵的列数:columns=matrix[0].length

       

    从最右上角开始找,初始化rowcolumn:row=0,column=columns-1;

       

    所以while条件为 row<rows&&column>=0

       

    如果找到,即matrix[row][column]=number,并将found置为true

       

    如果没找到,当前数大于Number,在左边找,column--

       

    当前数小于Number,在右边找,row++

       

    package findInMatrix;

       

    public class FindInMatrix {

       

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    test1();

    test2();

    }

       

    static void test1() {

    int matrix[][] = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 },

    { 6, 8, 11, 15 } };

    System.out.println(find(matrix, 1));

    }

       

    static void test2() {

    System.out.println(find(null, 7));

    }

       

    static boolean find(int[][] matrix, int number) {

       

    boolean found = false;

       

    if (matrix != null) {

       

    int rows = matrix.length;

    int columns = matrix[0].length;

    int row = 0;

    int column = columns - 1;

       

    while (row < rows && column >= 0) {

    if (matrix[row][column] == number) {

    found = true;

    break;

    } else if (matrix[row][column] > number) {

    --column;

    } else {

    ++row;

    }

    }

    }

    return found;

    }

    }

  • 相关阅读:
    OSError: cannot open resource(pillow错误处理)
    boost 库中文教程
    博客案例
    requests模块
    浅析Python中的struct模块
    面试基础知识点总结
    ant安装、环境变量配置及验证
    TestNG学习-001-基础理论知识
    selenium 常见面试题以及答案
    HTML5
  • 原文地址:https://www.cnblogs.com/keedor/p/4378945.html
Copyright © 2011-2022 走看看