力扣——搜索二维矩阵(python)

##题目

力扣——搜索二维矩阵(python)_第1张图片

##解析

  • 解法一:直接把二维列表变为一维列表,然后遍历进行比较
  • 解法二:将二位列表使用二分查找来加快效率 “ 0  1  2   3                                                                                                                                     4  5  6   7                                                                                                                                     8  9 10 11”   i = num //4  j = num % 4;不太稳定不建议使用

##代码

  • 解法一
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        for a_list in matrix:
            if target in a_list:
                return True
        return False
  • 解法二

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        h = len(matrix)#3
        if h == 0:
            return False
        w = len(matrix[0])#4
        if w == 0:
            return False
        left = 0
        right = h*w-1
        while left <= right:
            mid = (left+right)//2
            i = mid //w 
            j = mid % w
            if matrix[i][j] == target:
                return True
            elif matrix[i][j] > target:
                right = mid -1
            else:
                left = mid=1
        else:
            return False
  • ##运行效果

  • 力扣——搜索二维矩阵(python)_第2张图片

你可能感兴趣的:(力扣刷题,leetcode,矩阵,算法)