- 题目描述:
-
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
- 输入:
-
输入可能包含多个测试样例,对于每个测试案例,
输入的第一行为一个整数n(1<= n<=1000000):代表旋转数组的元素个数。
输入的第二行包括n个整数,其中每个整数a的范围是(1<=a<=10000000)。
- 输出:
-
对应每个测试案例,
输出旋转数组中最小的元素。
- 样例输入:
-
53 4 5 1 2
- 样例输出:
-
1
-
特殊情况://0 1 1 1 1 -> 1 1 1 0 1 首尾中间三个数相等的情况
-
二分查找失败,此时顺序查找即可
-
同样的问题,输入数据量大的时候,用cin输入会超时,改为scanf输入数据即可
-
#include <iostream> #include <cstdio> using namespace std; int array[1000000]; int main() { //freopen("i.txt","r",stdin); int n=0; int temp; // while(cin>>n&&(n>=1)&&(n<=1000000)) while(scanf("%d",&n)!=EOF&&(n>=1)&&(n<=1000000)) { for(int i=0;i<n;i++) { // cin>>temp; scanf("%d",&temp); array[i]=temp; } int s=0,e=n-1,m=(s+e)/2; if(array[s]<array[e])//初始就全局有序 { cout<<array[s]<<endl; continue; } while(s!=e-1) { //0 1 1 1 1 -> 1 1 1 0 1 首尾中间三个数相等的情况 if((array[m]==array[s])&&(array[m]==array[e])) { int result=array[s]; for(int j=s+1;j<=e;j++) { if(array[j]<result) result=array[j]; } cout<<result<<endl; break; } if(array[m]>array[s]) { s=m; m=(s+e)/2; } else { e=m; m=(s+e)/2; } } if(s==e-1) cout<<array[e]<<endl; } return 0; } /************************************************************** Problem: 1386 User: fuestck Language: C++ Result: Accepted Time:670 ms Memory:5424 kb ****************************************************************/