Leetcode: find_minimum_in_rotated_sorted_array

Source: Internet
Author: User

I. Question

Given an sorted array, the array may increase monotonically or may have a transformation.

(I. e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2)

The minimum number is required.

Ii. Analysis

This question is divided into two situations as described in the question.

1. Strictly monotonic increasing

2. There is an inflection point

We need to process the problem by case. Of course, we can traverse the problem directly, that is, scanning from start to end to find the minimum number.

1. When strictly monotonous, we can directly return the first element because it is sorted; or we can directly use the bipartite search.

2. When there is an inflection point, we can quickly find the minimum value in binary search.

In summary, two situations can improve efficiency, but they can be better handled directly as one case. And can pass.

 

class Solution {public:    int findMin(vector<int> &num) {    int min = num[0];        for(int i=1;i<num.size();i++){        if(num[i]>num[i-1])        min = num[i];        }         return min;    }};class Solution {public:    int findMin(vector<int> &num) {    if(num.size()==0) return 0;int sta=0;int flag;    int end=num.size()-1;    while(sta<end){    flag = (sta+end)/2;    if(num[flag]<num[end])    end=flag;    else     sta=flag+1;    }        return num[sta];    }};class Solution {public:    int findMin(vector<int> &num) {    int cou=num.size()-1;         //the numbers of num    if(num.size()==0) return 0;   //the num is null    if(num.size()==1) return num[0]; //num have a single numberint mid=0;int sta=0;       //the start int end=cou;     //the end if(num[sta]<num[end]) {     //Monotonically increasingreturn num[0];}else {             //There are situations inflection point while(sta<end){mid = (sta+end)/2;if(num[mid]<num[end])    end=mid;        else     sta=mid+1;}return num[end];        }    }};


Leetcode: find_minimum_in_rotated_sorted_array

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.