按照慣例,我搜索了谷歌和這裏的答案,但沒有找到任何幫助我的東西。請記住,這是不是作業,我正在爲測試而努力學習,並努力完成這個問題的答案。 有一個交替排序的數組,意味着偶數索引元素被排序並且奇數索引元素也被排序(從最小到最大數目)。 例如:現在找到一個交替排序陣列的2個相鄰陣列元素的可能組合
int a[] = {1,2,5,3,6,10,9};
,該問題要求寫一個布爾方法,接收陣列和的數,X,並返回true如果該數目是2個相鄰的「磚」的可能的組合和假如果不。例如:
x = 9;
FindX(a,9) -> true;
a[3](3) + a[4](6) = 9.
我寫我的方法,而且似乎與許多工作是IS一個可能的組合,但是當它應該返回false它卡住時的數量是在範圍2種可能的組合。
public static boolean FindX(int a[], int x){
if (a.length==1) { // The question specifies if it's an array with 1 element is should return false.
return false;
}
int i=(a.length-1)/2; // The middle index
int i2=i+1; // The adjacent index
for (; i>=0 && i2<a.length;){ // beginning of loop, if either index is out of bounds, terminates look
if (a[i]+a[i2]==x) { // once you reach the proper index (when x is within) it returns true
return true;
}
else if (a[i]+a[i2]>x){ // if x is smaller than current combo, make the new index in the new bounds
i = (i/2)+1;
i2 = i+1;
}
else if (a[i]+a[i2]<x){ // same as above boolean, but opposite situation
i = (i2+a.length)/2;
i2 = i+1;
}
}
return false;
}
每當我輸入一個可能的組合,它的工作。但是如果例如我將14(= a [3] (3) + a [4] (6))和16(= a [4] (6) + a [ 5] (10))它永遠循環,我不能想到一個正確的方式退出時,發生。如果該數字超出了可能的組合範圍,但不在範圍內,它確實會返回false,但是對於中間數字,我被卡住了。 在內存和時間複雜度方面,答案必須儘可能高效。
在此先感謝。
我只能想到O(N * logN)的解決方案。不知道它是否已經足夠快速(高效)。 –
@ThariqNugrohotomo線性搜索將起作用,所以我們需要改進。事實證明,二進制搜索正常工作。 – dasblinkenlight
我的意思是O(N * logN)結合了線性搜索和二元搜索。因此,對於奇數索引(線性)中的每個元素,我將從偶數索引(二進制)中的元素中找到它的「對」。 –