Leetcode解题报告:74. Search a 2D Matrix

题目大意:

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.

难度:Medium

解题思路: 由于这道题中,第 i+1 行的所有元素比第i行都大, 我们可以把这个二维数组简化为一个有序的一维数组。 在二维数组中,一个元素的行列坐标记为x,y,每行的元素个数记为n,行的数目记为m,那么在一维数组中,该元素对应的下标就是x*n+y,在一维数组中,元素按照大小已经排好序了,那么我们可以采取二分查找的方式寻找目标值。 取中间位置的元素为pivot,如果目标值就是这个元素,就返回true。如果目标值比pivot小,就用同样的方法搜索下标比pivot下标小的区间,如果比pivot大,就搜索下标大于pivot下标的区间,直到搜索到目标值返回true,或者区间的起始下标大于终点下标就可以认为数组中没有目标值。  

    具体操作中,我们可以从起始下标0,终止下标为数组的行数*数组的列数-1作为终点下标开始按照如上的思想递归地进行搜索,中间位置mid=(start+end)/2, 在二维数组中对应的位置为(mid/n,mid%n)其中n是每行的元素个数。

   这种方法的时间复杂度就是二分查找的时间复杂度,O(logn)

class Solution {
public:
bool helper(vector<vector<int>>& nums,int start,int end,int target)
{
	int mid=(start+end)/2;
	int x=mid/nums[0].size();
	int y=mid%nums[0].size();
	if(start>end)
	return false;
	if(nums[x][y]==target)
	{
		return true;
	}
	else if(nums[x][y]>target)
	{
		return helper(nums,start,mid-1,target);
	}
	else
		return helper(nums,mid+1,end,target);
}
bool searchMatrix(vector<vector<int>>& matrix, int target) {
	if(matrix.size()==0)
	return false;
    else 
    return	helper(matrix,0,matrix[0].size()*matrix.size()-1,target);
	        
}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值