[1] to prove safety offer. Find a two-dimensional array [by Python]

Find a two-dimensional array [by Python]

Title: (same as the length of each one-dimensional array) in a two-dimensional array, each row from left to right in order of ascending sort, to sort each column from top to bottom in increasing order. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

Ideas:

  First, select the top right corner of array numbers. If this number is equal to the number to find, lookup process ends; if the number is greater than looking for the array, excluding this figure where the column; if the number is less than the number to find, excluding the line where this number. That upper right corner if the number you are looking for is not in the array, then each time in a row or reject the Look of the array, so that each step can narrow the range to find, until you find the numbers you are looking for, or to find the range air.

For example:

If you find a number in a two-dimensional array 7, there is the return True, False if not found is returned.

First, 8 is greater than 7, one only needs to look at the left side region 8; then, 5 less than 7, one only needs to find the region 5 below; to find in this rule, to find if the same, then return True otherwise, it returns False.

Python implementation:

Copy the code
# -*- python3.6.6 -*-
# -*- JluTiger  -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        rows = len(array)
        cols = len(array[0])
        if rows >0 and cols >0:
            row = 0
            col = cols-1
            while row<rows and col>=0:
                if target == array[row][col]:
                    return True
                elif target <array[row][col]:
                    col -=1
                else:
                    row += 1
        return False

if name ==main:
target
= 15
array
= [[1,2,3],[4,5,6],[7,8,9],[10,12,13]]
answer
= Solution()
print(answer.Find(target,array))

Guess you like

Origin blog.csdn.net/qq_33487726/article/details/90715996