首页 > 其他 > 详细

Find Minimum in Rotated Sorted Array II

时间:2015-10-13 01:34:18      阅读:216      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!