[LeetCode] 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:

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

Example 2:

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

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 100
  • -104 <= matrix[i][j], target <= 104

搜索二维矩阵。

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是将input convert成一个一维数组,然后用二分法做。这题因为数组中元素的大小关系,所有的元素是可以组成一个有序的一维数组的,所以可以用二分法做。mid数字的坐标是 [mid / col][mid % col]

时间O(log mn), m和n是矩阵的长宽

空间O(1)

JavaScript实现

 1 /**
 2  * @param {number[][]} matrix
 3  * @param {number} target
 4  * @return {boolean}
 5  */
 6 var searchMatrix = function (matrix, target) {
 7     let row = matrix.length;
 8     let col = matrix[0].length;
 9     let start = 0;
10     let end = row * col - 1;
11     while (start <= end) {
12         let mid = Math.floor(start + (end - start) / 2);
13         let value = matrix[Math.floor(mid / col)][Math.floor(mid % col)];
14         if (value === target) {
15             return true;
16         } else if (value < target) {
17             start = mid + 1;
18         } else {
19             end = mid - 1;
20         }
21     }
22     return false;
23 };

 

Java实现

 1 class Solution {
 2     public boolean searchMatrix(int[][] matrix, int target) {
 3         int m = matrix.length;
 4         int n = matrix[0].length;
 5         int start = 0;
 6         int end = m * n - 1;
 7         while (start <= end) {
 8             int mid = start + (end - start) / 2;
 9             int cur = matrix[mid / n][mid % n];
10             if (cur == target) {
11                 return true;
12             } else if (cur > target) {
13                 end = mid - 1;
14             } else {
15                 start = mid + 1;
16             }
17         }
18         return false;
19     }
20 }

 

相关题目

74. Search a 2D Matrix

240. Search a 2D Matrix II

LeetCode 题目总结

posted @ 2019-11-05 02:08  CNoodle  阅读(454)  评论(0编辑  收藏  举报