問題:
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