首页 > 其他 > 详细

Find Minimum in Rotated Sorted Array II

时间:2015-06-21 18:22:53      阅读:198      评论:0      收藏:0      [点我收藏+]

Description:

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.

Code:

 1  int findMinElement(vector<int>& nums, int indexLeft, int indexRight)
 2     {
 3         if (indexLeft < indexRight)
 4         {
 5             if ( nums[(indexLeft+indexRight)/2] < nums[indexRight])
 6                 return findMinElement(nums, indexLeft, (indexLeft+indexRight)/2);
 7             else if ( nums[(indexLeft+indexRight)/2] > nums[indexRight])
 8                  return findMinElement(nums, (indexLeft+indexRight)/2+1, indexRight);
 9              else
10             {//此时不能判最小值在左边还右边,遍历判断
11                 int result = nums[indexLeft];
12                 for (int i = indexLeft+1; i <= indexRight; i++)
13                 {
14                     if ( nums[i] < result)
15                          result = nums[i];
16                 }
17                 return result;
18             }
19         }
20         else
21             return nums[indexLeft];
22     }
23     int findMin(vector<int>& nums) {
24         return findMinElement(nums, 0, nums.size()-1 );
25     }

 

Find Minimum in Rotated Sorted Array II

原文:http://www.cnblogs.com/happygirl-zjj/p/4592202.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!