[Nowcoder] Local minimum value position

Source: Internet
Author: User

Defines the concept of a local minimum. Arr has a length of 1 o'clock, arr[0] is the local smallest. If Arr has a length of N (n>1), if arr[0]<arr[1], then arr[0] is the local minimum; if arr[n-1]<arr[n-2], then arr[n-1] is the local smallest; if 0<i<n-1, Both arr[i]<arr[i-1] and arr[i]<arr[i+1], then Arr[i] is the local smallest.
Given an unordered array of arr, it is known that any two contiguous numbers in Arr are unequal, write a function, and simply return to any of the local smallest occurrences in arr.


If arr[0]<arr[1], then arr[0] is the local smallest;--return 0

If Arr[n-1]<arr[n-2], then arr[n-1] is the local smallest;--return 1

If arr[0] and arr[n-1] are not, then left = 1, right = n+2, Mid = (left+right)/2

If ARR[MID] < arr[mid+1] and arr[mid]<arr[mid-1], then return to mid

Otherwise there will be Arr[mid] < arr[mid+1] or arr[mid]<arr[mid-1], assuming Arr[mid] < arr[mid+1]

Because, arr[0]<arr[1], Arr[mid] < arr[mid+1], arr[1] to Arr[mid] than the existence of a local minimum, so repeated iteration. The time Complexity O (LGN) is better than the traversed O (n).


classsolution{ Public:        intGetlessindex (vector<int>arr) {              if(arr.size () = =0)                return-1; if(arr.size () = =1)                return 0; if(arr[0] < arr[1])                return 0; intSize =arr.size (); if(Arr[size-1] < arr[size-2])                returnSize-1; intLow =1; intHigh = size-2; intmid;  while(Low <High ) {Mid= (low + high)/2; if(Arr[mid] > arr[mid+1]) { low= mid+1; }                  Else if(Arr[mid] > arr[mid-1]) { high= mid-1; }                  Else                    returnmid; }            returnLow ; }};

[Nowcoder] Local minimum value position

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.