题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
类实现
class Solution:
def __init__(self, target, array):
self.target = target
self.array = array
def __Find_row(self,row):
n = len(row) - 1
_min = 0
_max = n
mid = n/2
# print 'mid _max',mid,_max
# TODO
if n == 0:
# print self.target,row[0]
if self.target == row[0]:
# print 'Equal=='
return True
else:
# print '??'
return False
if n > 0:
if self.target == row[mid]:
# print 'Equal'
return True
elif self.target < row[mid]:
# print 'lower'
if mid == _min:
return False
else:
return self.__Find_row(row[:mid])
else:
# if self.target > row[mid]:
# print 'bigger'
return self.__Find_row(row[mid+1:])
def Find(self):
Found = False
for row in self.array:
if self.__Find_row(row):
Found = True
break
return Found
print test_r
Test
# Test
from numpy import random as rd
rd.seed(233)
Test =[rd.randint(1,15) for i in range(15)]
print Test
for t in Test:
if Solution(t, [[1,2,3],[4,5,6],[7,8,9]]).Find():
print t,'Y'
else:
print t,'N'
Test2 =[i for i in range(10)]
print Test2
for t in Test2:
if Solution(t, [[1,2,3],[4,5,6],[7,8,9]]).Find():
print t,'Y'
else:
print t,'N'
输出
[8, 8, 6, 2, 13, 4, 6, 2, 4, 12, 5, 8, 2, 4, 7]
8 Y
8 Y
6 Y
2 Y
13 N
4 Y
6 Y
2 Y
4 Y
12 N
5 Y
8 Y
2 Y
4 Y
7 Y
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 N
1 Y
2 Y
3 Y
4 Y
5 Y
6 Y
7 Y
8 Y
9 Y