您的位置:首页 > 其它

[LeetCode] Find Minimum in Rotated Sorted Array II

2015-07-19 17:57 363 查看
This problem is more or less the same as Find Minimum in Rotated Sorted Array. And one key difference is as stated in the solution tag. That is, due to duplicates, we may not be able to throw one half sometimes. And in this case, we could just apply linear search and the time complexity will become
O(n)
.

The idea to solve this problem is still to use invariants. We set
l
to be the left pointer and
r
to be the right pointer. Since duplicates exist, the invatiant is
nums[l] >= nums[r]
(if it does not hold, then
nums[l]
will simply be the minimum). We then begin binary search by comparing
nums[l], nums[r]
with
nums[mid]
.

If
nums[l] = nums[r] = nums[mid]
, simply apply linear search within
nums[l..r]
.

If
nums[mid] <= nums[r]
, then the mininum cannot appear right to
mid
, so set
r = mid
;

If
nums[mid] > nums[r]
, then
mid
is in the first larger half and
r
is in the second smaller half, so the minimum is to the right of
mid
: set
l = mid + 1
.

The code is as follows.

class Solution {
public:
int findMin(vector<int>& nums) {
int l = 0, r = nums.size() - 1;
while (nums[l] >= nums[r]) {
int mid = (l & r) + ((l ^ r) >> 1);
if (nums[l] == nums[r] && nums[mid] == nums[l])
return findMinLinear(nums, l, r);
if (nums[mid] <= nums[r]) r = mid;
else l = mid + 1;
}
return nums[l];
}
private:
int findMinLinear(vector<int>& nums, int l, int r) {
int minnum = nums[l];
for (int p = l + 1; p <= r; p++)
minnum = min(minnum, nums[p]);
return minnum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: