题目描述
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
1 | [ |
Given target = 5
, return true
.
Given target = 20
, return false
.
这题需要用一个比较快的算法去在数组中查找数字。
我用的方法是一个最差时间复杂度为O(mlogn)的算法,竖着遍历数组,看每一行的首位两个元素的区间,如果target在这个区间内,就可以做一个记录。最后,对所有记录的数组进行二分查找,找到元素后直接返回。
代码实现
1 | class Solution { |