剑指 Offer 11. 旋转数组的最小数字

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof
示例 1:

输入:[3,4,5,1,2]
输出:1
示例 2:

输入:[2,2,2,0,1]
输出:0


func minInOrder(numbers []int, index1 int, index2  int) int {
    result := numbers[index1]
    for i := index1 + 1; i <= index2; i++ {
        if result > numbers[i] {
            result = numbers[I]
        }
    }

    return result
}

func minArray(numbers []int) int {
    index1 := 0
    index2 := len(numbers) - 1
    indexMid := index1

    for numbers[index1] >= numbers[index2] {
        if index2 - index1 == 1 {
            indexMid = index2
            break
        }

        indexMid = (index1 + index2) / 2

        if (numbers[index1] == numbers[index2] && 
            numbers[indexMid] == numbers[index1]) {
               return minInOrder(numbers, index1, index2)
        } 
           
        if numbers[indexMid] >= numbers[index1] {
            index1 = indexMid
        } else if numbers[indexMid] <= numbers[index2] {
            index2 = indexMid
        }
    }

    return numbers[indexMid]

}
剑指 Offer 11. 旋转数组的最小数字_第1张图片
image.png

你可能感兴趣的:(剑指 Offer 11. 旋转数组的最小数字)