校招面试题二维有序数组查找

给定一个二维整型矩阵,已知矩阵的每一行都按照从小到大的顺序排列,每一列也都按照从小到大的顺序排列。现在给出一个数,请写一个函数返回该数是否存在于矩阵中。

矩阵中出现的数字与需要查找的数(k)都为0~100000之间的整数,且矩阵的大小在3000*3000以内。

在保证正确性的基础上,请尽量给出比较高效的解法。请列出你的算法时间复杂度与空间复杂度分别是多少?

输入描述:

输入两个整数m,n, 且 0<m<=3000, 0<n<=3000。

接着输入一个vector<vector<int>> matrix矩阵,大小为m行n列,与一个int k,为需要查找的数字。

输出描述:

输出true或者false,true表示该数k存在于该matrix矩阵中,false表示该数k不存在于该matrix矩阵中。

输入例子1:

3 3
​​2 3 5
​​3 4 7
​​3 5 8
4

输出例子1:

true

例子说明1:

4位于矩阵的第二行第二列,故输出true
#include <iostream>
using namespace std;
const int N = 3500;
int arr[N][N];


bool find(int n, int m, int target) {
	int i = n - 1, j = 0;
	while (i>=0 && j<m) {
		if (arr[i][j] > target) {
			i--;
		}
		else if (arr[i][j] < target) {
			j++;
		}
		else
			return true;
	}
	return false;

}

int main()
{
	int n, m, target;
	scanf("%d %d", &n, &m);
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			scanf("%d", &arr[i][j]);
		}
	}

	scanf("%d", &target);
	if (find(n, m, target))
		printf("true\n");
	else
		printf("false\n");
}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/89197246