LeetCode:Find Minimum in Rotated Sorted Array

Problem:

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.

Subscribe to see which companies asked this question

 

 1 class Solution {
 2 public:
 3     int findMin(vector<int>& nums) {
 4         
 5         int first=0;
 6         int last=nums.size()-1;
 7         
 8         int result=INT_MAX;
 9         
10         while(first<=last)
11         {
12             int mid=(first+last)/2;
13             
14             //没有旋转的情况 
15             if(nums[first]<=nums[last])
16                 return min(nums[first],result);
17                 
18             else
19             {   
20                 //小于的情况
21                 if(nums[first]<=nums[mid])
22                 {  
23                     first=mid+1;
24                     
25                 }
26                 //大于的情况
27                 else
28                 {   
29                     result=nums[mid];
30                     last=mid-1;
31                     
32                 }
33                 
34             }
35         }
36         return result;
37     }
38 };

 

posted @ 2016-01-20 21:59  尾巴草  阅读(141)  评论(0编辑  收藏  举报