您的位置:首页 > 其它

文章标题

2015-12-25 13:16 806 查看
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:

1)Integers in each row are sorted in ascending from left to right.

2)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.

题意:

编写一个高效的算法,查询m*n矩阵中的某个值。这个矩阵具有以下属性:

1.每一行的整数从左到右按升序排序。

2.每一列的整数从上到下按升序排序。

解题思路:二分法

先二分查找第一列,找出目标值所在的行,再对所在行进行二分查找!

代码:

class solution
{
public:
bool searchMattrix(vector<vector<int>>&matrix,int target)
{
int m = matrix.size();//行数
int n = matrix[0].size();//列数
int index=binary_search_1(matrix,target,0,m-1);//对第一列进行二分查找,锁定所在行
if(index<0 || index>=m)
return false;
return binary_search_2(matrix[index],target,0,n-1);//对所在行进行二分查找
}
protected:
int binary_search_1(vector<vector<int>> &matrix, int target, int start, int end)    //先锁定target所在行
{
if(start >= end)
return start;
int mid = (start + end)/2;
if(target >= matrix[mid][0] && target < matrix[mid+1][0])
return mid;
else if(target < matrix[mid][0])
{
return binary_search_1(matrix,target,start,mid-1);
}
else
{
return binary_search_1(matrix,target,mid+1,end);
}
}
bool binary_search_2(vector<int> &row, int target, int start, int end)     //在锁定行中查找target
{
if(start>=end)
return row[start]==target;
int mid=(start+end)/2;
if(row[mid]==target)
return true;
else if(row[mid]<target)
return binary_search_2(row,target,mid+1,end);
else
return binary_search_2(row,target,start,mid-1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: