The smallest number of offer-rotating arrays

Source: Internet
Author: User

Topic:

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, a rotation of the array (3,4,5,1,2) bit {1,2,3,4,5}, the minimum value of the array is 1.


Basic idea:

Binary lookup, P1 point A[0],p2 point to a[len-1]. If A[MID]>A[P1], the minimum value is in the second half, p1=mid; if a[mid]<a[p2], the minimum value is in the first half, P2=mid.

Special cases:

Note: In both arrays, the first number, the last number, and the median number are 1, and we cannot determine whether the median number 1 belongs to the first ascending word group or the second incrementing word group.

This situation can only be found in sequential methods.


#include <iostream>using namespace Std;int mininorder (int a[],int index1,int index2) {int result = A[index1];for ( int i=index1+1;i<=index2;i++) {if (Result>a[i]) result=a[i];} return result;} int min (int a[],int len) {if (len<0) return 0;int index1=0;int index2=len-1;int indexmid=index1;//If the rotated array is itself, The default is Index1while (A[index1]>=a[index2]) {if (index2-index1==1) {indexmid=index2;break;} Indexmid= (INDEX1+INDEX2)/2;//if the Index1,index2 and indexmid three are equal, you can only search sequentially if (a[index1]==a[index2]&&a[indexmid]= =A[INDEX1]) return Mininorder (A,INDEX1,INDEX2), if (A[indexmid]>=a[index1]) Index1=indexmid;else if (A[indexMid] <=A[INDEX2]) Index2=indexmid;} return a[indexmid];} int main () {int a[]={3,4,5,1,2};int b[]={1,0,1,1,1};cout<<min (a,5) <<endl;cout<<min (b,5) << Endl;return 0;}



Sword refers to the smallest number of offer-rotated arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.