LeetCode

旋转数组的最小数字

2019-02-18  本文已影响0人  storm_lincoln

原题链接 旋转数组的最小数字

题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。


解题思路
采用二分查找法
C++具体代码

#include<iostream>
#include<vector>

int minNumberInRotateArray(std::vector<int> rotateArray) {
   if (rotateArray.size() == 0) return 0;
   int len = rotateArray.size();
   int low = 0;
   int high = len - 1;
   while (low < high) {
       int mid = low + (high-low) / 2;
       if (rotateArray[mid] > rotateArray[high]) {
           low = mid + 1;
       }
       else if (rotateArray[mid] == rotateArray[high]) {
           high = high - 1;
       }
       else
       {
           high = mid;
       }
   }
   return rotateArray[low];
}

void main() {
   int res = -1;
   std::vector<int> vec = { 1,1,1,0,1 };
   res = minNumberInRotateArray(vec);
   std::cout << res << std::endl;
   system("pause");
}
上一篇下一篇

猜你喜欢

热点阅读