来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix/

描述

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

示例 1:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
输出: true

示例 2:
输入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
输出: false

题解

  1. class Solution {
  2. public boolean searchMatrix(int[][] matrix, int target) {
  3. int m = matrix.length;
  4. if (0 == m) return false;
  5. int n = matrix[0].length;
  6. // 二分查找
  7. int left = 0, right = m * n - 1;
  8. int pivotIdx, pivotElement;
  9. while (left <= right) {
  10. pivotIdx = (left + right) / 2;
  11. pivotElement = matrix[pivotIdx / n][pivotIdx % n];
  12. if (target == pivotElement) {
  13. return true;
  14. } else if (target > pivotElement) {
  15. left = pivotIdx + 1;
  16. } else {
  17. right = pivotIdx - 1;
  18. }
  19. }
  20. return false;
  21. }
  22. }

复杂度分析

  • 时间复杂度 : 由于是标准的二分查找,时间复杂度为74. 搜索二维矩阵(Search a 2D Matrix) - 图1
  • 空间复杂度 : 74. 搜索二维矩阵(Search a 2D Matrix) - 图2