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:

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

Example 2:

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

难度:medium

题目:写算法在m * n的矩阵中查找给定的值。矩阵特征如下:
矩阵中的每行升序排列。
每行中的的第一个数大于其前一行的最后一个数。

思路:从最后一列中找出第一个大于target的值,并记录下当前行。然后对该行进行二分查找。

Runtime: 5 ms, faster than 73.46% of Java online submissions for Search a 2D Matrix.
Memory Usage: 38.8 MB, less than 0.96% of Java online submissions for Search a 2D Matrix.

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }
        int m = matrix.length, n = matrix[0].length, row = 0;
        for (int i = 0; i < m; i++) {
            row = i;
            if (matrix[i][n - 1] >= target) {
                break;
            }
        }
        
        return Arrays.binarySearch(matrix[row], target) >= 0;
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜


下一篇 »
78. Subsets