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.
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
.
解题方法:
每次找到二维数组最中间的数,将它与target比较,如果等于target则返回true;如果大于target,则这个数右面和下面组成的矩阵都大于target,在上面和左面的两个矩阵中重复进行与target比较;如果小于target,则这个数左边和上面组成的矩阵都小于target,在下面和右面的两个矩阵中重复进行与target比较。每次搜索都会减少矩阵大小的1/4.所以时间复杂度为log(4/3)^n。这是一个典型的分治算法,和二分法类似。
代码详情:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0) {
return false;
} else if (matrix[0].size() == 0) {
return false;
} else {
int flag = 0;
int i = matrix.size()-1;
int j = matrix[0].size()-1;
search(matrix,0,i,0,j,target,flag);
if (flag == 0)
return false;
else
return true;
}
}
void search(vector<vector<int>>& matrix, int x1, int x2, int y1, int y2, int target, int& flag) {
int x = (x1+x2)/2;
int y = (y1+y2)/2;
if (matrix[x][y] == target) {
flag=1;
} else if (matrix[x][y] < target) {
if (y+1 <= y2 && flag == 0) {
search(matrix, x1, x2, y+1, y2,target,flag);
}
if (x+1 <= x2 && flag == 0) {
search(matrix,x+1,x2,y1,y,target,flag);
}
} else if (matrix[x][y] > target) {
if (y-1 >= y1 && flag == 0) {
search(matrix, x1, x2, y1, y-1,target,flag);
}
if (x-1 >= x1 && flag == 0) {
search(matrix,x1,x-1,y,y2,target,flag);
}
}
}
};
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() == 0) {
return false;
} else if (matrix[0].size() == 0) {
return false;
} else {
int flag = 0;
int i = matrix.size()-1;
int j = matrix[0].size()-1;
search(matrix,0,i,0,j,target,flag);
if (flag == 0)
return false;
else
return true;
}
}
void search(vector<vector<int>>& matrix, int x1, int x2, int y1, int y2, int target, int& flag) {
int x = (x1+x2)/2;
int y = (y1+y2)/2;
if (matrix[x][y] == target) {
flag=1;
} else if (matrix[x][y] < target) {
if (y+1 <= y2 && flag == 0) {
search(matrix, x1, x2, y+1, y2,target,flag);
}
if (x+1 <= x2 && flag == 0) {
search(matrix,x+1,x2,y1,y,target,flag);
}
} else if (matrix[x][y] > target) {
if (y-1 >= y1 && flag == 0) {
search(matrix, x1, x2, y1, y-1,target,flag);
}
if (x-1 >= x1 && flag == 0) {
search(matrix,x1,x-1,y,y2,target,flag);
}
}
}
};