zoukankan      html  css  js  c++  java
  • 《剑指Offer》算法题——二维数组查找

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

    class Solution {
    public:
        bool Find(vector<vector<int> > array, int target) {
            int col = array.size();
            int i = 0;
            while (i < col)
            {
                int j = array[i].size()-1;//考虑边界条件
                if (j<0)
                    continue;
                if (target == array[i][j])
                {
                    return 1;
                }
                else if (array[i][j] > target)
                {
                    while (j > 0)
                    {
                        if (target == array[i][j])
                        {
                            return 1;
                        }
                        j--;
                    }
                }
                i++;
            }
            return 0;
        }
    };

    当我们运行时,需要测试边界条件:

    如果没考虑到这里,就会向下越界。该算法可以运行,但是这个算法超时:

    改进后算法如下:

    class Solution {
    public:
        bool Find(vector<vector<int> > array, int target) {
            int row = array.size();
            int col = 0;
            int totalcol = array[0].size();
            if (0 == row)
                return 0;
            row--;
            while (row >= 0 && col<totalcol)
            {
                if (target < array[row][col])
                    row--;
                else if (target > array[row][col])
                    col++;
                else
                    return 1;
            }
            return 0;
        }
    };

    运行通过:

  • 相关阅读:
    js 置顶操作
    js input输入数量控制
    js 时间倒计时
    html内容垂直居中
    大图片随浏览器水平居中显示
    img,display:inline相关间隙样式问题
    js淡入淡出轮换思想(1)
    js 禁止|阻止滚动条滚动
    kotlin学习--第一个kotlin项目
    jdk8+Mybatis3.5.0+Mysql读取LongBlob失败
  • 原文地址:https://www.cnblogs.com/predator-wang/p/5341940.html
Copyright © 2011-2022 走看看