[LeetCode] Find Minimum in Rotated Sorted Array (2 solutions)

Source: Internet
Author: User

Find Minimum in Rotated Sorted Array

Suppose a sorted array is rotated at some unknown to you beforehand.

(I. e .,0 1 2 4 5 6 7Might become4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.

 

Solution 1: brute-force method. Use the minimum element function in the algorithm library directly.

The whole vector needs to be traversed.

Class Solution {public: int findMin (vector <int> & num) {if (num. empty () return 0; vector <int>: iterator iter = min_element (num. begin (), num. end (); return * iter ;}};

 

Solution 2: Use the sorted information. If translation is done, a gap is displayed, that is, the jump from the maximum element to the minimum element. If there is no jump, it means there is no translation.

It can save a lot of time than the previous solution. On average, you do not need to traverse the vector.

Class Solution {public: int findMin (vector <int> & num) {if (num. empty () return 0; else if (num. size () = 1) return num [0]; else {for (vector <int >:: size_type st = 1; st <num. size (); st ++) {if (num [ST-1]> num [st]) return num [st];} return num [0] ;}};

[LeetCode] Find Minimum in Rotated Sorted Array (2 solutions)

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.