"Coding Interview Guide" - find a local minimum position in the array

[ Title ]

  Minimal definition of the concept of local: arr length is 1, arr [0] is a local minimum; when N (N> 1) length arr is, if arr [0] <arr [1], then arr [0] is a partial minimum, if arr [N - 1] <arr [N - 2], then arr [N - 1] is a local minimum; if 0 <i <N-1, both arr [i] <arr [i-1] , there arr [i] <arr [i + 1], then arr [i] is a local minimum

  Given unordered array arr, arr known that any two adjacent numbers not equal. Write a function, simply return any position arr a local minimum appears to
 

 1     public int getLocalMinIndex(int[] arr)
 2     {
 3         if(arr == null || arr.length == 0)
 4         {
 5             return -1;
 6         }
 7         if(arr.length == 1 || arr[0] < arr[1])
 8         {
 9             return 0;
10         }
11         if(arr[arr.length - 1] < arr[arr.length - 2])
12         {
13             return arr.length - 1;
14         }
15         int left = 1;
16         int right = arr.length - 2;
17         while(left < right)
18         {
19             int mid = (left + right) / 2;
20             if(arr[mid] > arr[mid - 1])
21             {
22                 right = mid - 1;
23             }
24             else if(arr[mid] > arr[mid + 1])
25             {
26                 left = mid + 1;
27             }
28             else
29             {
30                 return mid;
31             }
32         }
33         return left;
34     }

  Can not use the Find an orderly array half, as long as you can determine either side of half both sides there is certainly what you're looking for, you can use binary search

 

Source: Left Cheng Yun teacher "Programmer Code Interview Guide"

Guess you like

Origin www.cnblogs.com/latup/p/11018817.html