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

Find Minimum in Rotated Sorted Array

时间:2015-10-12 10:29:07      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

ERROR: control may reach end of non-void function

技术分享
 1 class Solution {
 2 public:
 3     int findMin(vector<int>& nums) {
 4         if(nums.empty()) return 0;
 5         
 6         return helper(nums, 0, nums.size() - 1);
 7     }
 8     
 9     int helper(vector<int>& nums, int left, int right){
10         if(left == right) return nums[left];
11         if(right - left == 1) return min(nums[left], nums[right]);
12         
13         int mid = left + (right - left) / 2;
14             
15         if(nums[left] < nums[right]) //didn‘t rotate
16             return nums[left];
17         if(nums[mid] > nums[left])
18             return helper(nums, mid, right);
19         if(nums[mid] < nums[left])
20             return helper(nums, left, mid);
21     }
22 };
23 
24     
View Code

 

 1 class Solution {
 2 public:
 3     int findMin(vector<int>& nums) {
 4         if(nums.empty()) return 0;
 5         
 6         return helper(nums, 0, nums.size() - 1);
 7     }
 8     
 9     int helper(vector<int>& nums, int left, int right){
10         if(left == right) return nums[left];
11         if((right - left) == 1) return min(nums[left], nums[right]);
12         
13         int mid = left + (right - left) / 2;
14             
15         if(nums[left] < nums[right]) //didn‘t rotate
16             return nums[left];
17         else if(nums[mid] > nums[left])
18             return helper(nums, mid, right);
19         else
20             return helper(nums, left, mid);
21     }
22 };
23 
24     

 

Find Minimum in Rotated Sorted Array

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4870738.html

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