[英]Search for an element in a circular sorted 2d matrix
我在 class 中收到了一個問題,我無法理解它。 我已經嘗試了好幾天,想不出一個 100% 有效的邏輯
我們被要求以可用的最佳復雜性來做這件事。 我發現行是按大小排序的,但是這個理論失敗了。
我想如果我能找到中間元素,我可以相應地移動指針,但這沒有任何意義。
我在想也許我應該找到每個象限的開始索引和最后一個索引,然后在里面搜索,但我不知道如何用二維數組來做到這一點
這是我到目前為止編寫的一段代碼(沒用)
public static boolean search (int [][] mat, int num) {
int midRowIndex =(mat.length-1)/2;
int midColIndex =(mat[0].length-1)/2;
int start = 0;
int end =(mat.length*mat[0].length)-1;
System.out.println("Mid index is: [" +midColIndex + "][" + midRowIndex + "]");
System.out.println("Number of indexes is: " +end);
System.out.println("Searching for: " +num );
while (start<end) {
if (mat[midRowIndex][midColIndex] == num)
return true;
if (mat[midRowIndex][midColIndex] < num)
if(midColIndex < mat.length)
midColIndex+=1;
else{
midColIndex=0;
midRowIndex+=1;
}
if (mat[midRowIndex][midColIndex] > num)
midRowIndex-=1;
start+=1;
}
return false;
}
我不是要直接回答,只是為了一些線索。
謝謝!
你可以在這里做的是二進制搜索的一種變體。
這是算法(也許它有一些小錯誤,但這是一般的想法):
For matrix a of size n x n, and searched value s:
evenIteration = true //as in even/odd
startX, startY = 0
endX, endY = n
while(endX >= startX && endY >= startY):
middleY = ((endY + startY)/2)
middleX = ((endX + startX)/2)
if evenIteration:
i = middleY - 1
j = middleX
Else:
i = endY - 1
j = startX
candidate = a[i][j]
if s == candidate:
Return i,j // We found the searched value!
if s < candidate:
if evenIteration:
endY = middleY
else:
endX = middleX
else:
if evenIteration:
startY = middleY
else:
startX = middleX
evenIteration = !evenIteration
嘗試理解這背后的邏輯,並在代碼中實現它。 編寫單元測試並調試代碼。 這將幫助您更好地理解算法。
如果您需要進一步解釋,請在評論中告訴我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.