# [剑指Offer] 旋转数组的最小数字

## 问题描述

NOTE：给出的所有元素都大于0，若数组大小为0，请返回0

## 分析

### 思路一

int minNumberInRotateArray(vector<int> rotateArray) {
int len = rotateArray.size();
if (len == 0) return 0;
int pre = rotateArray[0];
for(int i = 0; i < len; ++i) {
if (rotateArray[i] < pre) {
return rotateArray[i];
}

pre = rotateArray[i];
}
}

### 思路二

low 指向 左部分， high指向右部分

int minNumberInRotateArray(vector<int> rotateArray) {
if (rotateArray.size() == 0) return 0;
int low = 0, high = rotateArray.size() - 1;
int mid = 0;

// 数组有序时直接返回首元素
if (rotateArray[0] < rotateArray[high]) {
return rotateArray[0];
}

while (low < high-1) {
mid = (low + high) / 2;
if (rotateArray[mid] > rotateArray[low]) {
low = mid;
} else if (rotateArray[mid] < rotateArray[high]){
high = mid;
} else {
++low;
}
}

return rotateArray[high];
}

{1, 1, 1, 1, 1}
{1, 0, 1, 1, 1}
{3, 4, 5, 1, 2} // 普通
{1, 2, 3, 4, 5} // 旋转0

#include <iostream>
#include <vector>

using namespace std;

int minNumberInRotateArray(vector<int> rotateArray)
{
if (rotateArray.size() == 0) return 0;
int low = 0, high = rotateArray.size() - 1;
int mid = 0;

while (low < high) {
// 数组有序时直接返回首元素，low可能指到右部分的第一个元素（也就是min）
if (rotateArray[low] < rotateArray[high]) {
return rotateArray[low];
}
mid = (low + high) / 2;
if (rotateArray[mid] > rotateArray[low]) {
low = mid + 1; // 配合上面rotateArray[low] < rotateArray[high]的判断，能处理{1, 0, 1, 1, 1}
} else if (rotateArray[mid] < rotateArray[high]){
high = mid;
} else {
++low;
}
}

return rotateArray[low];
}

int main()
{
int a1[] = {1, 1, 1, 1, 1};
int a2[] = {1, 0, 1, 1, 1};
int a3[] = {3, 4, 5, 1, 2}; // 普通
int a4[] = {1, 2, 3, 4, 5}; // 旋转0

vector<int> input1(a1, a1+5);
vector<int> input2(a2, a2+5);
vector<int> input3(a3, a3+5);
vector<int> input4(a4, a4+5);

cout << minNumberInRotateArray(input1) << " expected: 1" << endl;
cout << minNumberInRotateArray(input2) << " expected: 0" << endl;
cout << minNumberInRotateArray(input3) << " expected: 1" << endl;
cout << minNumberInRotateArray(input4) << " expected: 1" << endl;
}

## References

posted @ 2020-05-24 23:12  arcsinW  阅读(94)  评论(0编辑  收藏  举报