lintcode 160 寻找旋转排序数组中的最小值 II

来源:互联网 发布:iphone mac地址伪装 编辑:程序博客网 时间:2024/04/27 08:57

假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。

你需要找到其中最小的元素。

数组中可能存在重复的元素。

样例

给出[4,4,5,6,7,0,1,2]  返回 0

解析:这个题目我们可以使用二分法的思想去解决,因为数组是有序的(分开的两部分)

#include <iostream>#include <vector>using namespace std;class Solution {public:/*** @param num: the rotated sorted array* @return: the minimum number in the array*/int findMin(vector<int> &num) {// write your code hereint len = num.size();if (len<1){return 0;}int mid = 0;int low = 0;int height = len-1;while (num[low]>=num[height]){if (height - low == 1){return num[height];}mid = (low + height) / 2;//如果low height mid的值相同,只能顺序查找if (num[low] == num[mid] && num[mid] == num[height] && num[height] == num[low]){return MinInOrder(num, low, height);}if (num[mid]>=num[low]){low = mid;}else if (num[height] >= num[mid]){height = mid;}}return num[mid];}int MinInOrder(vector<int> array, int low, int height){int result = array[low];for (int i = low + 1; i <= height;i++){if (result>array[i]){result = array[i];}}return result;}};int main(){int a[] = { 4, 4, 5, 6, 7, 0, 1, 2 };int len = sizeof(a) / sizeof(a[0]);vector<int> array(a, a + len);Solution s;cout << s.findMin(array);return 0;}


1 0
原创粉丝点击