-1

I found this problem on leetcode, I've solved it on my platform. For the tests I've used 1000 elements arrays, and never got an error. On leetcode platform it throws ArrayIndexOutOfBoundsException. If you look carefully, there is no way the elements a, b, or can n go further than array's length. This is the description of the problem:

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. You may assume no duplicate exists in the array.

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];        
    }
}
Julian F. Weinert
  • 7,076
  • 6
  • 56
  • 100

1 Answers1

-1
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);
    }
}

From coding interview.

Ryan
  • 2,697
  • 5
  • 32
  • 56