题解 | #二维数组中的查找#

二维数组中的查找

https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e


#方法一,20/21 组用例通过
#从对角线寻找对应行的方法,存在盲区,不正确
# class Solution:
#     def Find(self , target: int, array: List[List[int]]) -> bool:
#         # write code here
#         rows = len(array)
#         cols = len(array[0])
#         if array==[[]] :
#             return False
#         i=0
#         j=0
#从对角线寻找对应行的方法,存在盲区,不正确
#         while target>array[i][j] and i<rows-1 and j<cols-1 :
#             i=i+1
#             j=j+1
#             while target<array[i][j] and j>0:
#                     j=j-1
#         if array[i][j]==target:
#             return True
#         return False


#方法二 线性搜索
#class Solution:
    # def Find(self, target, array):
    #     if len(array) == 0:
    #         return False
    #     rows = len(array)
    #     cols = len(array[0])
    #     #从左下开始,
    #     left, down = 0, rows-1
    #     while left <cols and down>=0:
    #         tmp = array[down][left]
    #         if tmp == target:
    #             return True
    #         elif tmp <target:
    #             left +=1
    #         else:
    #             down-=1
    #     return False

#方法三 二分搜索
class Solution:
    def bisearch(self ,target,array):
        left=0
        right=len(array)-1
        while left<=right:
            mid=int((right+left)/2)
            if target==array[mid]:
                return True
            elif target>array[mid]:
                left = mid+1
            elif target<array[mid]:
                right=mid-1
        return False


    def Find(self , target: int, array: List[List[int]]) -> bool:
        # write code here
        rows = len(array)
        for i in range(rows):
            arr=array[i]
            result=self.bisearch(target,arr)
            if result==True:
                return True
        return False

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务