Title Link Address:
Http://ac.jobdu.com/problem.php?pid=1386
Topic 1386: Minimum number of rotated arrays
Time limit: 1 seconds memory limit: 32 trillion special problem: No submit: 6914 Resolution: 1534
Title Description:
Moves the first element of an array to the end of the array, which we call the rotation of the array. Enter a rotation of an incrementally sorted array, outputting the smallest element of the rotated array. For example, the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, and the minimum value of the array is 1.
Input:
The input may contain multiple test samples, for each test case,
The first behavior of the input is an integer n (1<= n<=1000000): The number of elements that represent the rotated array.
The second line of input includes n integers, where the range of each integer A is (1<=a<=10000000).
Output:
corresponding to each test case,
Outputs the smallest element in the rotated array.
Sample Input:
5
3 4 5) 1 2
Sample output:
1
Thinking Analysis:
There is no way to use the two-point search in the book, greedy to go directly to the first position less than the previous number of the line.
The analysis of the topic:
For an array that rotates K-bits, it can be divided into two sequential parts a[0: (n-k)] and a[(n-k + 1): N-2], the largest element is a[n-k], and the smallest element is A[n-k + 1].
So by traversing the rotated array a[0,1,... n-1] Find the junction element of two incrementing sub-arrays, if the junction element A[i] satisfies A[i] < a[i-1] (0<= i < n), then this element a[i] is the smallest number in the rotated array.
对于整个数组没旋转,那么会一直扫到数组结尾,可以进行特殊处理。不然性能下降。
The time complexity is O (n-k).
Space complexity O (1).
Code:
********************************* ----------------------------------- "Sword Point offer" nine degrees OJ1386: Minimum number of rotation array----------------------------------- Author: Pastoral, date:2015 email:[email protected]**********************************/#include <stdio.h>#include <string>#include <stack>#include <iostream>using namespace Std;#define MAX 1000005The first element of the 2nd increment sequence is the smallest element in the array void findminvalueinrotatearray (int a[],int n) {int i;int min = a[0]; Initial array[0] is the smallest elementFor (i = 0;i < n-1;i++) {if (A[i] > a[i + 1]) {min = a[i + 1];Break ; } }printf ("%d\n", min); }int Main () {int n;While (EOF! = scanf ("%d", &n)) {int A[max];for (int i = 0;i < n;i++) {scanf ("%d", &a[i]); }Findminvalueinrotatearray (a,n); }return 0;}/**************************************************************problem:1386language:c++result:acceptedtime:670 Msmemory:5356 KB****************************************************************/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Sword Point offer" nine degrees OJ1386: Minimum number of rotation array