题目1384:二维数组中的查找

九度OJ 点击打开链接 (剑指Offer第三题)

题目描述:

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

输入:

输入可能包含多个测试样例,对于每个测试案例,

输入的第一行为两个整数m和n(1<=m,n<=1000):代表将要输入的矩阵的行数和列数。

输入的第二行包括一个整数t(1<=t<=1000000):代表要查找的数字。

接下来的m行,每行有n个数,代表题目所给出的m行n列的矩阵(矩阵如题目描述所示,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。

输出:

对应每个测试案例,

输出”Yes”代表在二维数组中找到了数字t。

输出”No”代表在二维数组中没有找到数字t。

样例输入:
3 3
5
1 2 3
4 5 6
7 8 9
3 3
1
2 3 4
5 6 7
8 9 10
3 3
12
2 3 4
5 6 7
8 9 10
样例输出:
Yes
No
No
代码:C++代码一直超时,不知道为什么。改用C后ok。
/*
 * 题目1384:二维数组中的查找
 * 剑指Offer - 面试题3
 */

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

void find_number_in_array(int* arr, int rows, int cols, int n);

int main(int argc, char* argv[]) {
	int m, n, number;
	int* arr = (int*)malloc(sizeof(int)*1000001);
	while (cin >> m >> n) {
		scanf("%d", &number);
//		int* arr = new int[m * n];
		for (int i = 0; i != m; ++i) {
			for (int j = 0; j != n; ++j) {
				scanf("%d", &arr[i * n + j]);
//				cin >> arr[i * n + j];
			}
		}

		find_number_in_array(arr, m, n, number);
	}
}
void find_number_in_array(int* arr, int rows, int cols, int n) {
	int row = 0, col = cols - 1;
	while (row < rows && col >= 0) {
		if (arr[row * cols + col] > n)
			--col;
		else if (arr[row * cols + col] < n)
			++row;
		else if (arr[row * cols + col] == n) {
//			cout << "Yes" << endl;
			printf("Yes\n");
			return;
		}
	}
//	cout << "No" << endl;
	printf("No\n");
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值