您的位置:首页 > 其它

leetcode 33|81. Search in Rotated Sorted Array 1|2

2017-10-27 10:36 477 查看
33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order 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).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

思路:二分查找,找中间点和两边的大小关系

class Solution {
public:
int search(vector<int>& nums, int target)
{
if (nums.empty())
return -1;
int left = 0;
int right = nums.size() - 1;
int mid;

while (left + 1 < right)
{
mid = (right - left) / 2 + left;
if (nums[mid] == target)
return mid;
else if (nums[left] <= nums[mid])
{
if (nums[left] <= target && target <= nums[mid])
right = mid;
else
left = mid;
}
else
{
if (nums[left] <= target || target <= nums[mid])
right = mid;
else
left = mid;
}
}
//double check
if (nums[left] == target)
return left;
else if (nums[right] == target)
return right;
else
return -1;
}
};

81. Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":

What if duplicates are allowed?
Would this affect the run-time complexity? How and why?

Suppose an array sorted in ascending order 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
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
由于有重复元素,a[m]>=a[l],[l,m]是递增元素的条件就不成立。

       如果a[m]=a[l],l++

class Solution {
public:
bool search(vector<int>& nums, int target)
{
if (nums.empty()) return false;
int l = 0;
int r = nums.size() - 1;
while (l + 1 < r)
{
int m = ( r - l ) / 2 + l;
if (nums[m] == target)
return true;
else if (nums[l] < nums[m])
{
if (target >= nums[l] && target < nums[m])
r = m;
else
l = m;
}
else if (nums[l] == nums[m]) //关键,必须保证[l,m]是递增元素
{
l++;
}
else
{
if (target >= nums[l] || target < nums[m])
r = m;
else
l = m;
}
}
//double check
return nums[l] == target || nums[r] == target;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: