Featured image of post 剑指 Offer 11. 旋转数组的最小数字

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

题目描述

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。

给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。例如,数组 [3,4,5,1,2][1,2,3,4,5] 的一次旋转,该数组的最小值为 1。  

示例 1:

  • 输入:numbers = [3,4,5,1,2]
  • 输出:1

示例 2:

  • 输入:numbers = [2,2,2,0,1]
  • 输出:0

提示:

  • n == numbers.length
  • 1 <= n <= 5000
  • -5000 <= numbers[i] <= 5000
  • numbers 原来是一个升序排序的数组,并进行了 1n 次旋转

注意:本题与主站 154 题相同:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/

解法一:二分查找

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
func minArray(numbers []int) int {
    low := 0
    high := len(numbers) - 1
    for low < high {
        pivot := low + (high - low) / 2
        if numbers[pivot] < numbers[high] {
            high = pivot
        } else if numbers[pivot] > numbers[high] {
            low = pivot + 1
        } else {
            high--
        }
    }
    return numbers[low]
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/15 23:30:52
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计