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

Find Minimum in Rotated Sorted Array II

时间:2015-02-10 15:22:51      阅读:195      评论: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.

The array may contain duplicates.

解题思路:二分查找,首先由中点处查找不重复点

int Find(vector<int> &num, int first, int last)
{
	int mid = (first + last) / 2;
	int LeftIdx = mid;
	int RightIdx = mid;
	while (num[LeftIdx] == num[mid] && LeftIdx >= first)
		--LeftIdx;
	while (num[RightIdx] == num[mid] && RightIdx >= first)
		++RightIdx;
	if (LeftIdx<first){
		if (RightIdx>last)
			return num[mid];
		else
			return min(num[mid], Find(num, RightIdx, last));
	}
	else{
		if (RightIdx > last)
			return min(num[mid], Find(num, first, LeftIdx));
		else
			return min(Find(num, first, LeftIdx), min(Find(num, RightIdx, last),num[mid]));
	}
}
int findMin(vector<int> &num) {
	return Find(num, 0, num.size() - 1);
}


Find Minimum in Rotated Sorted Array II

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43702933

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