leedcode_153题——Find Minimum in Rotated Sorted Array(二分查找)

Find Minimum in Rotated Sorted Array

  Total Accepted: 44929 Total Submissions: 135513My Submissions

 

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

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

Find the minimum element.

You may assume no duplicate exists in the array.

 

Hide Tags
  Array Binary Search
Have you met this question in a real interview? 
Yes
 
No
 
     这道题采用二分查找的方法,将多种情况考虑进来就好了
 
#include<iostream>

#include<vector>

#include<math.h>

using namespace std;



int findMin(vector<int>& nums){

	int a,b,c;

	a=0;

	c=nums.size()-1;

	b=(a+c)/2;

	int mins=nums[0];

	while(1)

	{

		if((a+1)==c)

		{

			mins=min(mins,min(nums[a],nums[c]));

			break;

		}

		if(a==c)

		{

			mins=min(mins,nums[a]);

			break;

		}

		if(nums[a]<nums[b]&&nums[b]<nums[c])

		{

			mins=min(mins,nums[a]);

			break;

		}

	    if(nums[a]>nums[b]&&nums[b]>nums[c])

		{

			mins=min(mins,nums[c]);

			break;

		}	

		if(nums[a]<nums[b]&&nums[b]>nums[c])

		{

			a=b;

			b=(a+c)/2;

			continue;

		}

		if(nums[a]>nums[b]&&nums[b]<nums[c])

		{

			c=b;

			b=(a+c)/2;

			continue;

		}

	}

	return mins;

}

int main()

{

	vector<int> vec;

	vec.push_back(2);vec.push_back(3);vec.push_back(4);vec.push_back(5);vec.push_back(1);

    cout<<findMin(vec)<<endl;



}

  

你可能感兴趣的:(array)