【剑指offer】二维数组中的查找-python/C++

502 阅读1分钟

【题目描述】

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

【思路解析】

假设n行n列:

思路一:结合二维数组的从左到右,从上到下递增这一特殊性质,不断取数组右上角的值与目标相比。比目标大,则此列不再考虑,列减一;比目标小,则此行不再考虑,row加一。这种方式每次都会删去一行或者一列,时间复杂度能控制在O(n)以内。

思路2:对每一行执行一次二分查找,每次二分查找最大时间复杂度为O(logn),总的时间复杂度为nlog(n).

【代码】

C++:
class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int rows=array.size();
        int columns=array[0].size()-1;
        int row=0;
        while(row<rows&&columns>=0){
            if(array[row][columns]==target){
                return true;
            }else if(array[row][columns]>target){
                columns--;
            }else{
                row++;
            }
        }
        return false;
    }
};
python:
# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        rows=len(array)-1
        column=len(array[0])-1
        row=0
        while(row<=rows and column>=0):
            if array[row][column]==target:
                return True
            elif(array[row][column]>target):
                column-=1
            else:
                row+=1
        return False