Minimum number of rotation of the array: Array

Title Description

The beginning of an array of several elements moved to the end of the array, the array we call rotation.
A non-descending order of the input array of a rotation of the output rotary smallest element array.
For example, an array {3,4,5,1,2} {1,2,3,4,5} is a rotation of the array to a minimum.
NOTE: All the elements are given in greater than 0, if the array size is 0, return 0.

Problem-solving ideas

Using binary search.

int high = arr.length - 1;

int low = 0;

int mid = low + (high - low) / 2;

We need to consider three cases:

  1. When arr [mid]> arr [hjgh], it may be the case: [3, 4, 5, 6, 0, 1, 2], the minimum value must be in the right mid, low = mid + 1;
  2. When arr [mid] <arr [high] When, array similar [2,2,3,4,5,6,6], then the minimum number necessarily Array [mid] or mid left, because the right necessarily all is incremented, high = mid;
  3. When the array [mid] == array [high] When, array similar [1,0,1,1,1] or [1,1,1,0,1], then the minimum number or not is determined in the left mid to the right, then we had a a test, high = high - 1;

Reference Code

 1 public class Solution {
 2     public int minNumberInRotateArray(int [] array) {
 3         if(array.length == 0) {
 4             return 0;
 5         }
 6         int low = 0;
 7         int high = array.length - 1;
 8         while(low < high) {
 9             int mid = low + (high - low) / 2;
10             if(array[mid] > array[high]) {
11                 low = mid + 1;
12             } else if(array[mid] < array[high]) {
13                 high = mid;
14             } else {
15                 high = high - 1;
16             }
17         }
18         return array[low];
19     }
20 }

 

Guess you like

Origin www.cnblogs.com/carry6/p/11516859.html