卖萌的弱渣

I am stupid, I am hungry.

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.

Solution

  • Binary Search n * m matrix convert to an array => matrix[x][y] => a[x * m + y]

an array convert to n * m matrix => a[x] =>matrix[x / m][x % m];

  • Java
(Search-2D-Matrix.java) 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
public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix==null || matrix.length==0)
            return false;
        int m = matrix.length;
        int n = matrix[0].length;
        int l = 0;
        int r = m*n-1;

        while (l <= r){
            int mid = l+(r-l)/2;
            int row = mid/n;
            int col = mid%n;
            if (matrix[row][col] == target)
                return true;
            else if (matrix[row][col] < target)
                l = mid+1;
            else
                r = mid-1;

        }
        return false;

    }
}
  • Python
(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
28
29
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """

        if not matrix:
            return False

        row = len(matrix)
        col = len(matrix[0])

        if target<matrix[0][0] or target>matrix[row-1][col-1]:
            return False

        l = 0
        r = row*col-1

        while l<=r:
            m = (l+r)/2
            if matrix[m/col][m%col] == target:
                return True
            elif matrix[m/col][m%col] < target:
                l = m+1
            else:
                r = m-1
        return False