剑指Offer_11_旋转数组的最小数字
廖家龙 用心听,不照做

❗️LeetCode_154_寻找旋转排序数组中的最小值2

❗️LeetCode_153_寻找旋转排序数组中的最小值

题目描述:

1
2
3
4
5
6
7
8
9
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。  

示例:

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

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

解法1:二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int minArray(vector<int>& numbers) {

int low = 0, high = numbers.size() - 1;

while (low <= high) { //条件都是<=

int pivot = low + (high - low) / 2; //取中点

//表示右边是递增的
if (numbers[pivot] < numbers[high]) high = pivot;

//表示左边是递增的
else if (numbers[pivot] > numbers[high]) low = pivot + 1;

//如果本题数组中元素各不相同,这个条件也要带上
else high -= 1; //特殊情况:[1,1,1,1,2,1,1,1]
}

return numbers[low];
}
};