用剑指offer上的方法做真题发现复杂度太高,只能ac 60%……
真题链接:https://www.nowcoder.com/practice/dd5b5b2df5f84bae9b26c99a0a8f8660
最后参考讨论区的解答:https://www.nowcoder.com/questionTerminal/dd5b5b2df5f84bae9b26c99a0a8f8660?f=discussion
用set()容器ac过了
方法一:
使用矩阵元素逐个比较。
# -*- coding:utf-8 -*-
class Solution:
# array 二维列表
def Find(self, target, array):
# write code here
if not array:
return False
row = len(array)
col = len(array[0])
r = row-1
c = 0
while r >=0 and c < col:
if array[r][c] < target:
c += 1
elif array[r][c] > target:
r -= 1
elif array[r][c] == target:
return True
return False
方法二 :
用set()方法首先对数组去重。
lst = list(map(int,input().split()))
m = lst[0]
n = lst[1]
mat = set()
for i in range(m):
tmp = list(map(int,input().split()))
for j in tmp:
mat.add(j)
num = int(input())
if num in mat:
print('true')
else:
print('false')