剑指offer - 二维数组的查找

左心房为你撑大大i 提交于 2020-02-03 03:33:10

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

解法一:暴力搜索

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int rowcount = array.size();
        int colcount = array[0].size();
        
        if(rowcount == 0 || colcount == 0) return false;
        
        for(int i = 0; i < rowcount; i++)
        {
            for(int j = 0; j < colcount; j++)
            {
                if(array[i][j] == target) return true;
            }
        }
        return false;
    }
};

暴力搜索第一个版本的 O(n2)O(n^{2}),在第二个版本中同样借助暴力搜索我们可以将时间复杂度缩减为 O(n)O(n):

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

解法二:行上借助二分查找

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int rowcount = array.size();
        int colcount = array[0].size();
        int l, h, mid;
         
        if(rowcount == 0 || colcount == 0) return false;
         
        for(int i = 0; i < rowcount; i++)
        {
            l = 0; h = rowcount - 1;
            while(l <= h)
            {
                mid = (l + h) / 2;
                if(array[i][mid] < target) l = mid + 1;
                else if(array[i][mid] > target) h = mid - 1;
                else return true;
            }
        }
        return false;
    }
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!