-001- search algorithm to find the two-dimensional array

Article Directory

Title Description

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

Here Insert Picture Description

analysis

Depending on the size characteristics of the two-dimensional array to 寻找数字 7:
Here Insert Picture Description
a two-dimensional array 行数为n, 列数为mthen:
maintenance of two index 时间复杂度O(n+m)variables 空间复杂度为O(1), .

Code

# -*- coding:utf-8 -*-
class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        if not array:
            return False
        
        numRow = len(array) - 1
        numCol = len(array[0]) - 1
        
        row = 0
        col = numCol
        while col >= 0 and row<= numRow:
            if array[row][col] < target:
                row += 1
            elif array[row][col] > target:
                col -= 1
            else:
                return True
        return False
Published 219 original articles · won praise 85 · Views 140,000 +

Guess you like

Origin blog.csdn.net/z_feng12489/article/details/103180571