How do I search for a number in a 2d array sorted left to right and top to bottom?

问题:

I was recently given this interview question and I'm curious what a good solution to it would be.我最近收到了这个面试问题,我很好奇有什么好的解决方案。

Say I'm given a 2d array where all the numbers in the array are in increasing order from left to right and top to bottom.假设我有一个二维数组,其中数组中的所有数字都是从左到右、从上到下递增的。

What is the best way to search and determine if a target number is in the array?搜索和确定目标数字是否在数组中的最佳方法是什么?

Now, my first inclination is to utilize a binary search since my data is sorted.现在,我的第一个倾向是使用二分搜索,因为我的数据已排序。 I can determine if a number is in a single row in O(log N) time.我可以在 O(log N) 时间内确定一个数字是否在一行中。 However, it is the 2 directions that throw me off.然而,这是两个方向让我失望。

Another solution I thought may work is to start somewhere in the middle.我认为可能有效的另一个解决方案是从中间的某个地方开始。 If the middle value is less than my target, then I can be sure it is in the left square portion of the matrix from the middle.如果中间值小于我的目标,那么我可以确定它位于矩阵中间的左边正方形部分。 I then move diagonally and check again, reducing the size of the square that the target could potentially be in until I have honed in on the target number.然后我沿对角线移动并再次检查,减少目标可能所在的正方形的大小,直到我磨练了目标数字。

Does anyone have any good ideas on solving this problem?有没有人有解决这个问题的好主意?

Example array:示例数组:

Sorted left to right, top to bottom.从左到右,从上到下排序。

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

解决方案:

参考: https://stackoom.com/en/question/AJNo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章