Minimum number of rotation of the array: Algorithms explanations

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.

Problem-solving ideas

Rotation array can be divided in half rotation of the new array containing a minimal element, and a non-decreasing sorted array. The new rotation of the array elements of the array is half the original array, thereby reducing the scale of the problem in half the time complexity of the algorithm of this binary nature of O (logN) (For convenience, here log2N written logN).

At this time, the problem lies in two arrays divided in half to determine which one is obtained rotating array, which array a non-decreasing. It is easy to know non-decreasing first element of the array must be smaller than equal to the last element.

Solved by modifying the binary search algorithm (L Representative low, m Representative mid, h Representative high):

  • When nums [m] <= nums [h], represents a [m, h] within the array is non-decreasing interval array, [l, m] in the array is rotating array section, then h = m orders;
  • Otherwise, [m + 1, h] array within the array is a rotating section, so that l = m + 1.
public int minNumberInRotateArray(int[] nums) {
    if (nums.length == 0)
        return 0;
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] <= nums[h])
            h = m;
        else
            l = m + 1;
    }
    return nums[l];
}

If the array element allows repeated, there will be a special case: nums [l] == nums [m] == nums [h], in which solution can not be determined at this time interval, the need to switch to sequential search. For example, the array {1,1,1,0,1}, l, m and h are a number of points, this time interval would not know what the minimum number 0.

public int minNumberInRotateArray(int[] nums) {
    if (nums.length == 0)
        return 0;
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[l] == nums[m] && nums[m] == nums[h])
            return minNumber(nums, l, h);
        else if (nums[m] <= nums[h])
            h = m;
        else
            l = m + 1;
    }
    return nums[l];
}

private int minNumber(int[] nums, int l, int h) {
    for (int i = l; i < h; i++)
        if (nums[i] > nums[i + 1])
            return nums[i + 1];
    return nums[l];
}

reference

CyC2018

Guess you like

Origin www.cnblogs.com/yueshutong/p/11571495.html
Recommended