练习第二天

Z4 二维数组中的查找

我的暴力解法,时间空间复杂度都比较小,但还可以直接进行优化

class Solution:
    def Find(self , target: int, array: List[List[int]]) -> bool:
        # write code here
        # 暴力解法,在这肯定会超出时间限制
        for i in array:
            if target in i:
                return True
        # 其他的情况
        return False

别人的时间复杂度较小的解法,核心思路使用查找,两个游标进行有序数字的划分处理,时间更少一些,且不需要开辟额外的相关空间

#使用查找的思路进行代码的编写
class Solution:
    def Find(self , target: int, array: List[List[int]]) -> bool:
        # write code here
        # 排除特殊的情况
        if len(array)==0:
        	return False
        n = len(array) # 获取字符串的行
        if len(array[0])==0:
        	return False
        m = len(array[0]) # 获取字符串的列长度
        i = n-1
        j = 0
        while i>=0 and j < m:
        	# 从左下角的第一个元素进行相应的判断
            if array[i][j]<target:# 目标元素在右边
            	# 往右走
                j = j+1
            elif array[i][j]>target:# 目标元素在上边
            	# 往上奏走
                i = i-1
            else:
            	return True
            	
        return False