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

Find Minimum in Rotated Sorted Array II

时间:2015-10-13 01:35:06      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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.

The array may contain duplicates.

 

Analyse: add the situation where nums[mid] == nums[left].

Runtime: 8ms

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

 

Find Minimum in Rotated Sorted Array II

标签:

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

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