題目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");
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章