码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Find Minimum in Rotated Sorted Array

时间:2016-01-20 22:31:27      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

LeetCode:Find Minimum in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/5146754.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!