zoukankan      html  css  js  c++  java
  • 剑指offer:面试题3、二维数组中的查找

    题目描述

    在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

    代码示例

    public class Offer3 {
        public static void main(String[] args) {
            int[][] matrix = {
                    {1, 2, 3, 4 },
                    {5, 6, 7, 8 },
                    {9, 10,11,12},
                    {13,14,15,16}
            };
            Offer3 testObj = new Offer3();
            System.out.println(testObj.find(matrix, 6));
            System.out.println(testObj.find(matrix,18));
    
        }
    
        public boolean find(int[][] matrix, int target) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return false;
            }
            int rows = matrix.length;
            int cols = matrix[0].length;
            int r = 0;
            int c = cols - 1;
            //从右上角开始
            while (r <= rows - 1 && c >= 0) {
                if (target == matrix[r][c]) {
                    return true;
                } else if (target > matrix[r][c]) {
                    r++;
                } else {
                    c--;
                }
            }
            return false;
        }
    }
    
    
  • 相关阅读:
    webstorm配置github 以及本地代码上传github。
    日期控件------moment.js
    图片查看器
    日期
    配置一个node服务器
    git代码管理
    vue
    javascript (字符串, 数组, 对象 , 日期 和 操作元素节点 动画 定时器)
    html css
    JS常用方法
  • 原文地址:https://www.cnblogs.com/ITxiaolei/p/13138663.html
Copyright © 2011-2022 走看看