2014-10-26 65 views
-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];   
    } 
} 

回答

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

coding interview

相關問題