卖萌的弱渣

I am stupid, I am hungry.

Search a 2D Matrix

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.

Example

Consider the following matrix:

1
2
3
4
5
[
    [1, 3, 5, 7],
    [10, 11, 16, 20],
    [23, 30, 34, 50]
]

Given target = 3, return true.

Challenge

O(log(n) + log(m)) time

Solution

  • Time: O(logn + logm), Space: O(1) If A in (0,cols*rows), then matrix[A/cols][A%cols] could represent 2d matrix
(Search-A-2D-Matrix.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
    """
    @param matrix, a list of lists of integers
    @param target, an integer
    @return a boolean, indicate whether matrix contains target
    """
    def searchMatrix(self, matrix, target):
        # write your code here
        if not matrix or not matrix[0]:
            return False

        rows = len(matrix)
        cols = len(matrix[0])
        # a in [0,m*n-1]
        # matrix[i][j] = matrix[a/cols][a%cols]
        front = 0
        end = rows*cols-1

        while front <= end:
            mid = (front+end)/2
            if matrix[mid/cols][mid%cols] == target:
                return True
            elif matrix[mid/cols][mid%cols] < target:
                front = mid+1
            else:
                end = mid-1
        return False