Offer the smallest number of rotation of the array to prove safety

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.

Thinking

It uses a binary search
to consider three cases:

  • array [mid] <array [r], on the left in this case a certain minimum number of mid
  • array [mid] = array [r], the minimum number of not appear at this time to the left or right. So one by one to find, for example, [1,0,1,1,1]
  • array [mid]> array [r], in this case a certain minimum number of mid right

Reference Code

import java.util.ArrayList;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        int l = 0;
        int r = array.length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2; 
            if (array[mid] < array[r]) {
                r = mid;  
            } else if (array[mid] == array[r]) {
                r -= 1;
            } else {
                l = mid + 1;
            }
        }
        return array[l];
    }
}
Released seven original articles · won praise 0 · Views 1352

Guess you like

Origin blog.csdn.net/Incanus_/article/details/105242784