CCI: Find in Matrix

Given a matrix in which each row and each column is sorted, write a method to find an element in it.

第一反应是取矩阵中间元素折半,可以去掉1/4的区域,不过这样一来剩下的就是两个矩阵了。虽然也可以解决问题,有些复杂。简单一些,O(m+n)的方案吧。

注意二维数组做参数的用法,折腾了好几次,有时间再看看有没有更好的方式。

bool findInMatrix(int A[][5], int rows, int cols, int target) {
	int i = 0;
	int j = cols - 1;
	while (i < rows && j >= 0) {
		if (A[i][j] == target) {
			return true;
		}
		else if (A[i][j] > target) {
			--j;
		}
		else {
			++i;
		}
	}

	return false;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int rows = 3, cols = 5;
	int A[3][5] = {
		{1, 8, 12, 20, 30},
		{4, 9, 13, 25, 32},
		{6, 11,19, 28, 40},
	};

	
	cout << "Number 0 " << (findInMatrix(A, rows, cols, 5) ? "found" : "not found") << endl;
	cout << "Number 19 " << (findInMatrix(A, rows, cols, 19) ? "found" : "not found") << endl;
	cout << "Number 25 " << (findInMatrix(A, rows, cols, 25) ? "found" : "not found") << endl;
	cout << "Number 40 " << (findInMatrix(A, rows, cols, 40) ? "found" : "not found") << endl;
	cout << "Number 45 " << (findInMatrix(A, rows, cols, 45) ? "found" : "not found") << endl;

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值