Question
- leetcode: Search a 2D Matrix | LeetCode OJ
- lintcode: (28) Search a 2D Matrix
Problem Statement
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.
Example
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3
, return true
.
Challenge
O(log(n) + log(m)) time
Problem solution-one binary search VS two binary search
- One binary search -Since the matrices are arranged in ascending order, a two-dimensional matrix can be converted into a one-dimensional problem. Make appropriate changes to the original binary search (find rows and columns). The time complexity is $$O(log(mn))=O(log(m)+log(n))$$
- Two binary searches-press line first Then search by column, that is, two binary searches. The time complexity is the same.
One binary search
Python
1 |
class Solution:
|
C++
1 |
class Solution {
|
Java
The lower bound binary template.
1 |
public class Solution {
|
Source code analysis
The classic binary search template (lower bound) can still be used, just pay attention to the subscript assignment.
- First, do exception handling for the input, not only taking into account that matrix is null, but also that the length of matrix[0] is also 0.
- Because the change of lb must be smaller than target, it is judged in else.
Complexity analysis
Binary search, $$O(log mn)$$.
twice dichotomy
Python
1 |
< pre>class Solution : def search_matrix(self, matrix, target): if not matrix or not matrix[0]: return False # first pos >= target st, ed = 0, len(matrix)- 1 while st + 1 mid = (st + ed) / 2 if matrix[mid][-1] == target:< /span> st = mid elif matrix[mid ][-1] st = mid else: ed = mid if matrix[st][-1] >= target : row = matrix[st] elif span> matrix[ed][-1] >= target: row = matrix[ed]< /span> else: return False # binary search in row st, ed = 0, len(row)-1 while st + 1 mid = (st + ed) / 2 if row [mid] == target: return True span> elif row[mid] st = mid else: ed = mid return row[st] == target or row[ed] == target |
Source code analysis
- First find the line of
first position
, and the last element of this line is greater than or equal to target - Find target in this line
complexity analysis
Binary search, $$O(log m + log n)$ $
Original: Large Column Search a 2D Matrix