【面试题】寻觅旋转排序数组中的最小值
【面试题】寻找旋转排序数组中的最小值
题目描述
假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。你需要找到其中最小的元素。http://www.lintcode.com/zh-cn/problem/find-minimum-in-rotated-sorted-array/
解题思路
基本思想采用二分查找,不过首先要判断这个排序数组是否直接有序,如果是0 1 2 3 4 5 6 7这样的数组,最小值就是第一个值;接着就采用二分法来查找
代码实现
class Solution {
public:
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
int findMin(vector<int> &num) {
// write your code here
int len = num.size();
int low = 0;
int high = len - 1;
if(num[low] < num[high])
return num[low];
while(high - low > 1)
{
int mid = (high + low) / 2;
if(num[mid] > num[low])
{
low = mid;
}
else
{
high = mid;
}
}
return num[high];
}
};
class Solution {
public:
/**
* @param num: a rotated sorted array
* @return: the minimum number in the array
*/
int findMin(vector<int> &num) {
// write your code here
int len = num.size();
int low = 0;
int high = len - 1;
int min_index = low;
while(num[low] >= num[high])
{
if(high - low == 1)
{
min_index = high;
break;
}
int mid = (high + low) / 2;
if(num[low] < num[mid])
low = mid;
else
high = mid;
}
return num[min_index];
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。