01- dimensional array lookup

Topic 1: (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.

2 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.

3 Code:

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     # array 二维列表
 4     def Find(self, target, array):
 5         # write code here
 6         rows = len(array)
 7         cols = len(array[0])
 8         
 9         if rows > 0 and cols > 0:
10             row = 0
11             col = cols - 1
12             while row < rows and col >= 0:
13                 if target == array[row][col]:
14                     return True
15                 elif target < array[row][col]:
16                     col -= 1
17                 else:
18                     row += 1
19         return False

 4 cow brush the question off network platform: https://www.nowcoder.com/ta/coding-interviews

Guess you like

Origin www.cnblogs.com/WJZheng/p/11129636.html