GuilinDev

Lc0074

05 August 2008

74 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 1:

1
2
3
4
5
6
7
8
Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

1
2
3
4
5
6
7
8
Input:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
Output: false

题意和分析

在_m_ x _n_矩阵中寻找一个target,矩阵左右和上下都是升序排好的,并且上一行最后一个数不会大于下一行的第一个数,找到就返回true,否则返回false。这个题的解法可以把二维矩阵转换成一维矩阵,然后查找时注意一下二维矩阵下标的定位即可。

跟Binary Search 一样,Time:O(log(m*n))m和n分别是行数和列数;也可以说成O(logn),n为二维矩阵的原书个数; Space:O(1)。

代码

模板

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
30
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        int left = 0;
        int right = rows * cols - 1;
        
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            // 对列数整除和取余,相当于当作一个一维数组来处理,每一段就是列数
            int x = mid / cols; // 在第几段就是第几行
            int y = mid % cols; // 剩几个就是在某一段上的第几列
            if (target == matrix[x][y]) {
                return true;
            } else if (target > matrix[x][y]) {
                left = mid;
            } else {
                right = mid;
            }
        }
        if (target == matrix[left / cols][left % cols] || target == matrix[right / cols][right % cols]) {
            return true;
        }
        return false;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) {
            return false;
        }

        int start = 0;
        int rows = matrix.length, cols = matrix[0].length;//注意这里没有-1
        int end = rows * cols - 1; //处理成一维数组的总长

        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (matrix[mid / cols][mid % cols] == target) {//中间值的下标值除以列数值就等于中间值所位于的行数(总长==rows*cols-1),取余列数值则等于中间值所处的列数,从而可以定位到二维矩阵的两个下标
                return true;
            } else if (matrix[mid / cols][mid % cols] < target) {//target在“右边”
                start = mid + 1;
            } else {//target在“左边”
                end = mid - 1;
            }
        }
        return false;
    }
}