您的位置:首页 > 其它

Search a 2D Matrix II -- leetcode

2015-09-29 21:51 381 查看
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.

For example,

Consider the following matrix:
[
[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
.

算法一,

1. 选择左下角的元素

2,如果该值大于target,则可以确定,在当前行中,不存在target。从而可以排除掉一行。

3,如果该值小于target,则可以确定,在当前列中,不存在target。从而可以排除掉一列。

4,对剩余矩阵,重复步骤2,3. 直到找到,或者剩余矩阵为空。

执行过程,就是不断的排除下面的行,或者左边的列。

由于每次循环都排除掉一行或者一列,故算法时间复杂度为O(m+n)。

另外,除了选择左下角,也可以选择右上角。

在leetcode上实际执行时间为260ms。

class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty())
return false;
const int M = matrix.size();
const int N = matrix[0].size();
int row = M-1;
int col = 0;
while (row >= 0 && col < N) {
if (target < matrix[row][col])
--row;
else if (target > matrix[row][col])
++col;
else
return true;
}
return false;
}
};

算法二, 折半。
选取矩阵的中心点,与target作比较。

1. 如果该值小于target,则可以排除掉左上角4分之1矩阵。继续在剩余4分之3矩阵中查找。

2. 如果该值大于target,则可以排除掉右上角4分之1矩阵。

在leetcode上实际执行时间为556ms。

class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty())
return false;
return searchMatrix(matrix, 0, 0, matrix.size()-1, matrix[0].size()-1, target);
}

bool searchMatrix(vector<vector<int>>& matrix, int x1, int y1, int x2, int y2, int target) {
if (x1 > x2 || y1 > y2)
return false;

const int x = x1 + (x2 - x1) / 2;
const int y = y1 + (y2 - y1) / 2;
if (matrix[x][y] == target)
return true;
else if (matrix[x][y] > target)
return searchMatrix(matrix, x1, y1, x-1, y2, target) || searchMatrix(matrix, x, y1, x2, y-1, target);
else
return searchMatrix(matrix, x1, y+1, x2, y2, target) || searchMatrix(matrix, x+1, y1, x2, y, target);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息