Java 旋转排序数组中的最小值ArrayIndexOutOfBoundsException
我在leetcode上发现了这个问题,我已经在我的平台上解决了它。在测试中,我使用了1000个元素数组,但从未出现错误。在leetcode平台上,它抛出ArrayIndexOutOfBoundsException。如果仔细观察,元素a、b或n不可能超过数组的长度。以下是问题的描述: 假设排序后的数组在您事先不知道的某个轴上旋转。 (即,01 2 4 5 6 7可能成为4 5 6 7 0 1 2)。 找到最小元素。 您可以假定数组中不存在重复项Java 旋转排序数组中的最小值ArrayIndexOutOfBoundsException,java,arrays,rotation,binary,indexoutofboundsexception,Java,Arrays,Rotation,Binary,Indexoutofboundsexception,我在leetcode上发现了这个问题,我已经在我的平台上解决了它。在测试中,我使用了1000个元素数组,但从未出现错误。在leetcode平台上,它抛出ArrayIndexOutOfBoundsException。如果仔细观察,元素a、b或n不可能超过数组的长度。以下是问题的描述: 假设排序后的数组在您事先不知道的某个轴上旋转。 (即,01 2 4 5 6 7可能成为4 5 6 7 0 1 2)。 找到最小元素。 您可以假定数组中不存在重复项 public class Solution {
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];
}
}
公共类解决方案
{
公共int findMin(int[]num)
{
int a=0;
int b=num.length-1;
int n=(a+b)/2;
while(true)
{
如果(num[n]
公共静态int findMin(int[]num){
返回帮助程序(num,0,num.length-1);
}
公共静态int-helper(int[]num,int-endLeft,int-endRight){
if(endLeft==endRight)
返回数值[endLeft];
如果((右端-左端)==1)
返回Math.min(num[endLeft],num[endRight]);
int middleIndex=endLeft+(endRight-endLeft)/2;
int middle=num[middleIndex];//中间值
if(num[endLeft]数值[endLeft]){
//向右走
返回帮助程序(num、middleIndex、endRight);
}否则{
//向左走
返回帮助程序(num、endLeft、middleIndex);
}
}
从
public static int findMin(int[] num) {
return helper(num, 0, num.length - 1);
}
public static int helper(int[] num, int endLeft, int endRight) {
if (endLeft == endRight)
return num[endLeft];
if ((endRight - endLeft) == 1)
return Math.min(num[endLeft], num[endRight]);
int middleIndex = endLeft + (endRight - endLeft) / 2;
int middle = num[middleIndex]; // middle value
if (num[endLeft] < num[endRight]) {
return num[endLeft];
} else if (middle > num[endLeft]) {
// go right side
return helper(num, middleIndex, endRight);
} else {
// go left side
return helper(num, endLeft, middleIndex);
}
}