Wins the Offer-6. The minimum number of rotation of the array (C ++ / Java)

topic:

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.

analysis:

This question and LeetCode on 153, 154 is the same. Array elements 153 is not simply duplicated, to allow the array 154 there are duplicate elements.

Here the array is non-descending order of direct input requirements, and so 154 is the same problem.

LeetCode 153. Find Minimum in Rotated Sorted Array find the minimum rotation sorted array (C ++)

LeetCode 154. Find Minimum in Rotated Sorted Array II to find the minimum value in sorted array rotating II (C ++)

Analysis may need to see the venue and to analyze 153,154 in view of the subject.

program:

C++

class Solution {
public:
    int minNumberInRotateArray(vector<int> rotateArray) {
        if(rotateArray.empty())
            return 0;
        return find(rotateArray, 0, rotateArray.size()-1);
    }
    int find(vector<int> &nums, int l, int r){
        if(nums[l] < nums[r] || l == r)
            return nums[l];
        int mid = l + (r - l) / 2;
        return min(find(nums, l, mid), find(nums, mid+1, r));
    }
};

Java

import java.util.ArrayList;
import java.util.*;
public class Solution {
    public int minNumberInRotateArray(int [] array) {
        if(array.length == 0)
            return 0;
        return find(array, 0, array.length-1);
    }
    public int find(int[] array, int l, int r){
        if(array[l] < array[r] || l == r)
            return array[l];
        int mid = l + (r - l) / 2;
        return Math.min(find(array, l, mid), find(array, mid+1, r));
    }
}

 

Guess you like

Origin www.cnblogs.com/silentteller/p/11832273.html