LeetCode 74. Search a 2D Matrix
Description
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 target = 13 Output: false
矩阵中有序存地放着一些数字,查找是否存在某个数字。
Solution
二分法(Binary Search)
下面代码使用两次二分查找,先找出在哪一行,再对该行进行二分查找。
亦有先计算元素个数:total = m x n
,再对total
进行二分查找的解法。
设二分时所以为index
,对应元素坐标为(index/m, index%m)
。
|
|