题目描述(Medium)
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
题目链接
https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
算法分析
二分查找,需要判断好左右边界,这里主要是先判断出递增子序列,然后以递增子序列作为判断条件,确定左右边界;
若出现A[mid] == A[first]时,不能确定递增的情况,则++first跳过该重复元素。
提交代码:
class Solution {
public:
bool search(vector<int>& nums, int target) {
if (nums.empty()) return false;
int beg = 0, end = nums.size() - 1;
int mid;
while (beg <= end)
{
mid = (beg + end) / 2;
if (nums[mid] == target)
return true;
if (nums[mid] > nums[beg])
{
if (target >= nums[beg] && target < nums[mid])
end = mid - 1;
else
beg = mid + 1;
}
else if (nums[mid] < nums[beg])
{
if (target > nums[mid] && target <= nums[end])
beg = mid + 1;
else
end = mid - 1;
}
else
//跳过重复元素
++beg;
}
return false;
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, vector<int>& nums, int target, bool expected)
{
if (testName != nullptr)
printf("%s begins: \n", testName);
Solution s;
bool result = s.search(nums, target);
if (result == expected)
printf("passed\n");
else
printf("failed\n");
}
int main(int argc, char* argv[])
{
vector<int> array1 = { 2, 5, 6, 0, 0, 1, 2 };
Test("Test1", array1, 0, true);
vector<int> array2 = { 2, 5, 6, 0, 0, 1, 2 };
Test("Test2", array2, 3, false);
vector<int> array3 = { 2, 5, 6, 0, 0, 1, 2 };
Test("Test3", array3, 2, true);
vector<int> array4 = { 1, 3, 1, 1, 1 };
Test("Test4", array4, 3, true);
return 0;
}