Search a 2D Matrix(medium)

102人阅读 评论(0)

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.

For example,

Consider the following matrix:

[
[1,   3,  5,  7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]


Given target = 3, return true.

在一个二维矩阵中找到给定的值。矩阵从上到下从左到右有序

与剑指offer里面的一个题类似，思路是从右上角元素开始遍历，每次遍历中若与target相等则返回true；若小于则行向下移动；若大于则列向左移动。时间复杂度m+n

class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i = 0, j = matrix[0].size() - 1;

while (i < matrix.size() && j >= 0)
{
if (target == matrix[i][j])
return true;
else if (target < matrix[i][j])
j--;
else
i++;
}

return false;
}
};

第二种方法：二分法确定target可能在第几行出现。再用二分法在该行确定target可能出现的位置。时间复杂度O(logn+logm)

class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int left = 0;
int right = matrix.size()-1;
if(left != right)
{
while(left<=right)
{
int middle = left + (right-left)/2;
if(matrix[middle][0] < target)
{
left = middle+1;
}
else if(matrix[middle][0] > target)
{
right = middle-1;
}
else
{
return true;
}
}
}
if(right == -1)
{
return false;
}
else
{
int row = right;
int left = 0;
int right = matrix[row].size()-1;
while(left<=right)
{
int middle = left + (right-left)/2;
if(matrix[row][middle] < target)
{
left = middle+1;
}
else if(matrix[row][middle] > target)
{
right = middle-1;
}
else
{
return true;
}
}
return false;
}

}
};


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：20093次
• 积分：861
• 等级：
• 排名：千里之外
• 原创：58篇
• 转载：67篇
• 译文：1篇
• 评论：0条
评论排行