LeetCode: 240. Search a 2D Matrix II

题目描述

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
2
3
4
5
6
7
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

这题需要用一个比较快的算法去在数组中查找数字。

我用的方法是一个最差时间复杂度为O(mlogn)的算法,竖着遍历数组,看每一行的首位两个元素的区间,如果target在这个区间内,就可以做一个记录。最后,对所有记录的数组进行二分查找,找到元素后直接返回。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0)
return false;
if (matrix[0].size() == 0)
return false;

int startIndex = -1;
int endIndex = 0;
for (endIndex = 0; endIndex < matrix.size(); endIndex++) {
if (startIndex == -1 && matrix[endIndex][0] <= target && matrix[endIndex][matrix[0].size()-1] >= target)
startIndex = endIndex;
if (matrix[endIndex][0] > target)
break;
}

if (startIndex == -1)
return false;

for (int i = startIndex; i <= endIndex && i < matrix.size(); i ++) {
int left = 0;
int right = matrix[0].size()-1;

if (left == right && matrix[i][left] == target)
return true;

while (left <= right) {
int mid = (left + right) / 2;
if (matrix[i][mid] == target)
return true;
else if (matrix[i][mid] < target)
left = mid + 1;
else
right = mid - 1;
}
}
return false;
}
};