-
- 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
-
-
Analysis:
-
-
The array after the rotation of the array can actually be divided into two parts, the preceding word group is greater than or equal to the following word group. The smallest number is exactly the dividing line of two sub-arrays. We can find the time complexity of O (LOGN) with a binary search. We use two pointers, respectively, in the array, the first element should be greater than or equal to the last element (not necessarily, there are special cases). If the middle element is greater than or equal to the first element, the minimum number is in the second half, and if the middle element is less than or equal to the last element, the smallest number is the first half.
-
-
Here are two special cases to note:
-
-
1. If there are 0 elements in front of the sorted array, move to the back.
-
-
2. If the sorted array has the same element. For example, if the sorted array is {0,1,1,1,1}, the rotated array can be {1,0,1,1,1} or {1,1,1,0,1}, you cannot directly determine which part of the minimum number is in the end.
-
-
-
-
Implementation code:
-
#include <cstdio> #include <cstring> #include <cstdlib>int a[1000001];int midinorder (int k[],int L, int r) {int res = k[l]; for (int i = l+1; I <= R; i++) {if (res > k[i]) res = k[i]; } return res; int searchmin (int k[],int l,int r) {int mid = L; while (K[l] >= K[r]) {if (r-l = = 1) {mid = R; Break } mid = L + (r-l)/2; if (k[l] = = K[r] && k[l] = = K[mid]) {return midinorder (k,l,r); } if (K[mid] >= k[l]) L = mid; else if (K[mid] < k[r]) R = Mid; } return K[mid];} int main () {//Freopen ("D:\\1.txt", "R", stdin); int n; while (scanf ("%d", &n)! = EOF) {for (int i = 0; i < n; i++) {scanf ("%d", &a[i]); } int min = Searchmin (a,0,n-1); printf ("%d\n", min); } return 0;}
Minimum number of rotated array