从谷歌的面试问题问题

2023-09-11 03:22:53 作者:我有疑心病i

可能重复:   Given二维数组排序从左至右,从上到下递增的顺序,什么是搜索目标数量的最佳方法是什么?

下面被要求在谷歌的采访:

The following was asked in a Google interview:

您将得到一个二维数组存储整数,垂直和水平方向排列。

You are given a 2D array storing integers, sorted vertically and horizontally.

写一个方法,作为输入一个整数,输出布尔话说整数是否在数组中

Write a method that takes as input an integer and outputs a bool saying whether or not the integer is in the array.

什么是做到这一点的最好方法是什么?什么是它的时间复杂度?

What is the best way to do this? And what is its time complexity?

推荐答案

我要问的细节意味着什么是启动来分类的垂直和水平

I would start by asking details about what it means to be "sorted vertically and horizontally"

如果该矩阵排序的方式,每一行的最后一个元素是小于下一行的第一个元素,可以运行在第一列上的二进制搜索,找出在什么行这个数字,并然后运行该行上的另一个二进制搜索。这个算法将需要为O(log C +登录R)的时间,其中C和R,行和列的分别的数目。使用对数的特性,可以写为○(日志(C * R))的,这是相同的为O(log N)时,如果N是数组中元素的数量。这是几乎相同处理阵一维和在其上运行的二进制搜索。

If the matrix is sorted in a way that the last element of each row is less than the first element of the next row, you can run a binary search on the first column to find out in what row that number is, and then run another binary search on the row. This algorithm will take O(log C + log R) time, where C and R are, respectively the number of rows and columns. Using a property of the logarithm, one can write that as O(log(C*R)), which is the same as O(log N), if N is the number of elements in the array. This is almost the same as treating the array as 1D and running a binary search on it.

但是,基质可能的方式,每一行的最后一个元素不大于下一行的第一个元素少进行排序:

But the matrix could be sorted in a way that the last element of each row is not less than the first element of the next row:

1 2 3 4 5 6 7 8  9
2 3 4 5 6 7 8 9  10
3 4 5 6 7 8 9 10 11

在这种情况下,你可以同时运行某种水平的垂直二进制搜索的:

In this case, you could run some sort of horizontal an vertical binary search simultaneously:

测试的第一列的中间数。如果它低于目标,考虑它上面的行。如果是较大的,可以考虑下面的那些; 测试首先考虑线的中间数。如果是少了,考虑它留下列。如果是较大的,考虑这些的权利; 车床,冲洗,重复,直到你找到一个,还是留给你没有更多的需要考虑的因素;

此方法也对数上的元素的数量。

This method is also logarithmic on the number of elements.