Sword refers to offer The first question is to find whether there is a specified integer value in a two-dimensional array (Python version)

 

Title description

In a two-dimensional array (each one-dimensional array has the same length), each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer to determine whether the array contains the integer.

Idea: In the rule array line ------ the left "right,

                                 Column -------- Up "Down,

Search from the right, if the target value is greater than the value on the right, find the maximum value in the next column (the rightmost value);

If the target value is less than the rightmost value (maximum value) of the current column, the target value can only exist in this column (and above rows);

 

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        if array==[]:
            return False
        row=len(array)
        col=len(array[0])
        if isinstance(array,list)!=True:
            return False
        if isinstance(target,int)!=True:
            return False
        i=col-1
        j=0
        while i>=0 and j< row:
            if array[j][i]> target:
                i-=1
            elif array[j][i] < target:
                j+=1
            else:
                return True
        return False

Guess you like

Origin blog.csdn.net/guyu1003/article/details/103733898