zoukankan      html  css  js  c++  java
  • 【剑指Offer】二维数组中的查找

    题目描述

    在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
     
    解法一:暴力
    时间复杂度O(mn)
    class Solution {
    public:
        bool Find(int target, vector<vector<int> > array) {
            int n = array.size(), m = array[0].size();
            for(auto a : array){
                for(auto b : a){
                    if(b == target) return true;
                }
            }
            return false;
        }
    };

     解法二:

    根据题目的意思,每一层行的数都是从左到右递增,并且每一列也都是从上到下递增,因此可以从左下角或者右上角开始找,本篇从左下角开始找,当选择的数 < target时,则向右边继续找,当选择的数 > target时,则向上继续找,一步步缩小搜索范围。

    时间复杂度O(m+n)

    class Solution {
    public:
        bool Find(int target, vector<vector<int> > array) {
            int maxrow = array.size();
            int maxcol = array[0].size();
            int i = maxrow - 1; //当前行数
            int j = 0; //当前列数
            while(j < maxcol && i >= 0){
                if(array[i][j] == target) return true;
                else if(array[i][j] < target) j++;
                else i--;
            }
            return false;
        }
    };
  • 相关阅读:
    Node.js安装及环境配置(windows)
    table
    检测浏览器
    ickeck插件
    全国三级联动
    css3-calc用法
    jQuery Portamento 滑动定位
    canvas版《俄罗斯方块》
    canvas入门级小游戏《开关灯》思路讲解
    css3 matrix 2D矩阵和canvas transform 2D矩阵
  • 原文地址:https://www.cnblogs.com/whisperbb/p/11689439.html
Copyright © 2011-2022 走看看