?LeetCode刷題實戰(zhàn)74:搜索二維矩陣
算法的重要性,我就不多說了吧,想去大廠,就必須要經(jīng)過基礎(chǔ)知識和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做?搜索二維矩陣,我們先來看題面:
https://leetcode-cn.com/problems/search-a-2d-matrix/
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
題意


解題
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
class?Solution:
????def?searchMatrix(self, matrix: List[List[int]], target: int)?-> bool:
????????import?numpy as?np
????????arr = np.array(matrix)
????????# 通過numpy可以直接reshape
????????arr = arr.reshape((-1, ))
????????l, r = 0, arr.shape[0]
????????if?r == 0:
????????????return?False
????????# 套用二分
????????while?l+1?< r:
????????????m = (l + r) >> 1
????????????if?arr[m] <= target:
????????????????l = m
????????????else:
????????????????r = m
????????return?arr[l] == target
正經(jīng)做法
class?Solution:
????def?searchMatrix(self, matrix: List[List[int]], target: int)?-> bool:
????????n = len(matrix)
????????if?n == 0:
????????????return?False
????????
????????m = len(matrix[0])
????????if?m == 0:
????????????return?False
????????
????????# 初始化,左開右閉,所以設(shè)置成-1, n-1
????????l, r = -1, n-1
????????
????????while?l+1?< r:
????????????mid = (l + r) >> 1
????????????# 小于target的時候移動左邊界
????????????if?matrix[mid][m-1] < target:
????????????????l = mid
????????????else:
????????????????r = mid
????????????????
????????row = r
????????
????????# 正常的左閉右開的二分
????????l, r = 0, m
????????
????????while?l+1?< r:
????????????mid = (l + r) >> 1
????????????if?matrix[row][mid] <= target:
????????????????l = mid
????????????else:
????????????????r = mid
????????????????
????????return?matrix[row][l] == target
優(yōu)化
class?Solution:
????def?searchMatrix(self, matrix: List[List[int]], target: int)?-> bool:
????????n = len(matrix)
????????if?n == 0:
????????????return?False
????????
????????m = len(matrix[0])
????????if?m == 0:
????????????return?False
????????
????????l, r = 0, m*n
????????
????????while?l+1?< r:
????????????mid = (l + r) >> 1
????????????# 還原行號和列號
????????????x, y = mid // m, mid % m
????????????if?matrix[x][y] <= target:
????????????????l = mid
????????????else:
????????????????r = mid
????????return?matrix[l // m][l % m] == target
上期推文:
