Leetcode#74. Search a 2D Matrix
Problem
You are given an m x n
integer matrix matrix
with the following two properties:
- Each row is sorted in non-decreasing order.
- The first integer of each row is greater than the last integer of the previous row.
Given an integer target
, return true
if target
is in matrix
or false
otherwise.
You must write a solution in O(log(m * n))
time complexity.
Example 1:
!https://assets.leetcode.com/uploads/2020/10/05/mat.jpg
1 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 |
Example 2:
!https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg
1 | Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 |
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
10^4 <= matrix[i][j], target <= 10^4
Solve
這題一樣就binary search
法1
1 | class Solution: |
Time Complexity: O(log(mn))
Space Complexity: O(1)
法2
比第一種還快些
1 | class Solution: |
Time Complexity: O(log(m) + log(n))
Space Complexity: O(1)
O(log(m) + log(n)) < O(log(mn))
所以第二種方法比較快
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Imisky!
評論