[Sword offer] 11 The smallest number of the rotating array

One, the problem

1. Move the first elements of an array to the end of the array, which we call the rotation of the array. Input a rotation of an ascending array, and output the smallest element of the rotated array. For example, the array [3,4,5,1,2] is a rotation of [1,2,3,4,5], and the minimum value of the array is 1.

2. Examples

Input: [3,4,5,1,2]
Output: 1

Input: [2,2,2,0,1]
Output: 0

Two, the solution

1. Violence Law

Start traversing from the element with subscript 0

For each comparison, if the current element is larger than the next adjacent element, the corresponding next element is the minimum value

If there is no 2 in the last element in the query, the subscript element is the smallest element.

2. Dichotomy

Store elements in order (required)

package com.haoxiansheng.demo01.SwordfingerOffer;

import lombok.extern.slf4j.Slf4j;

import java.util.Vector;

/**
 * @author flame
 * @data 2020/10/24
 */
@Slf4j
public class MinArrayDemo {
    
    
    public static void main(String[] args) {
    
    
        int [] arr = {
    
    2, 3, 4, 5, 0, 1};
        log.info("minArray=>{}", minArray(arr));
    }

    // 暴力匹配  + 二分查找
    // 时间复杂度为 O(n)
    // 空间复杂度:O(1)
    public static int minArray(int [] numbers) {
    
    
        int left = 0;
        int right = numbers.length -1;

        if (right == 0) {
    
    
            return numbers[0];
        }

        while (left < right) {
    
    
            int mid = left + (right - left) / 2;
            if (numbers[mid] > numbers[right]) {
    
    
                left = mid + 1;
            } else if(numbers[mid] < numbers[right]) {
    
    
                right = mid;
            } else if (numbers[mid] == numbers[right]) {
    
    
                right --; // 暴力缩减范围
            }
        }
        return numbers[left];
    }
}

Guess you like

Origin blog.csdn.net/qq_40996741/article/details/109268287