74. 搜索二维矩阵

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

 

示例 1:

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true

示例 2:

 

 

输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false

 

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

 0

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        a=[]
        for i in matrix:
            a+=i
        return target in a

 1

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        def binarySearch(arr, l, r, x):
            while l <= r:
                mid = l + (r - l) // 2;
                # Check if x is present at mid
                if arr[mid] == x:
                    return mid
                # If x is greater, ignore left half
                elif arr[mid] < x:
                    l = mid + 1
                # If x is smaller, ignore right half
                else:
                    r = mid - 1
            return -1
      
        a=[]
        for i in matrix:
            a+=i
        return binarySearch(a, 0, len(a)-1, target)!=-1

 2

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        def binarySearch(a, x): 
            i = bisect_left(a, x) 
            if i != len(a) and a[i] == x: 
                return i 
            else: 
                return -1
      
        a=[]
        for i in matrix:
            a+=i
        return binarySearch(a, target)!=-1

3

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        for i in range(len(matrix)):
            if i<len(matrix)-1:
                if matrix[i][0]<=target and matrix[i+1][0]>target:
                    for j in matrix[i]:
                        if j==target:
                            return True
            else:
                if matrix[i][0]<=target and matrix[i][-1]>=target:
                    for j in matrix[i]:
                        if j==target:
                            return True
        return False

 

posted @ 2021-03-30 19:35  XXXSANS  阅读(47)  评论(0编辑  收藏  举报