二维数组的查找
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
分析
重点在于二维数组的顺序性
题解
一、运行时间: 514 ms 占用内存:6328K
# -*- coding:utf-8 -*- class Solution: # array 二维列表 def Find(self, target, array): # write code here for row in array: if row == []: return False if target < row[0]: return False if target in row: return True
二、 运行时间: 455 ms 占用内存:5732K
# -*- coding:utf-8 -*- class Solution: # array 二维列表 def Find(self, target, array): # write code here row = len(array)-1 col = len(array[0])-1 i = row j = 0 while(i>=0 and j<=col): if target > array[i][j]: j += 1 elif target < array[i][j]: i -= 1 else: return True return False
三、运行时间: 220 ms 占用内存:5724K 状态:答案正确
# -*- coding:utf-8 -*- class Solution: # array 二维列表 def Find(self, target, array): # write code here col = len(array[0])-1 for row in array: if row == []: return False if target < row[0]: return False else: #二分法 i = 0 j = col while(i<=j): mid = (i+j)//2 if target>row[mid]: i = mid+1 elif target<row[mid]: j = mid-1 else: return True