-1
我在leetcode上發現了這個問題,我已經在我的平臺上解決了它。對於測試,我使用了1000個元素數組,並且從未出現錯誤。在leetcode平臺上,它拋出ArrayIndexOutOfBoundsException。如果仔細觀察,元素a,b或n不可能超出數組的長度。這是對問題的描述:旋轉排序數組中的最小值ArrayIndexOutOfBoundsException
假設已排序的數組在預先未知的某個關鍵點處旋轉。 (即,0 1 2 4 5 6 7可能變成4 5 6 7 0 1 2)。 找到最小元素。 您可能會認爲數組中沒有重複。
public class Solution
{
public int findMin(int[] num)
{
int a = 0;
int b = num.length - 1;
int n = (a + b)/2;
while (true)
{
if (num[n] < num[n+1] && num[n] < num[n-1])
break;
if (num[a] < num[b])
{
b = n;
n = (a + n)/2 + 1;
}
else
{
a = n;
n = (b + n)/2;
}
}
return num[n];
}
}