#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
/*
问题:
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.
分析:这道题目仍然是程序员面试金典的题目。题目指出课呢个存在重复的元素。
首先明确如何搜索:我们需要确定左半边和右半边哪一边是有序的,然后根据被查找元素
如果在有序的这一部分中,就在该有序部分中查找;否则,在另外一部分中查找。
1】如果发现左边元素和中间元素相同,此时判断如果左边和右边元素不同,那么就在左半部分查找;
2】如果左边=中间=右边,先查找左边,然后查找右边。
时间复杂度仍然为O(logN)和之前非重复的情况应该时间是一样的。只不过多了1】和2】的处理
设数组为A,初始下标为low , mid , high
输入:
7(数组元素个数) 3(待查找元素)
4 5 6 7 0 1 2
7 5
4 5 6 7 0 1 2
6 3
2 2 2 2 4 5
6 4
2 3 2 2 2 2
输出:
false
true
false
false
关键:
1 递归的大判断条件:
//这里如果low = high,会造成mid相等,会陷入左边=中间=右边的死循环
if(low < high)
只需要最后判断一下
//这里low = high,只需要再找一次,因为当前元素还没有找过
if(nums.at(low) == target)
{
return true;
}
else
{
return false;
}
*/
class Solution {
public:
bool searchRotation(vector<int>& nums, int target, int low , int high)
{
if(nums.empty() || low > high || low < 0 || high >= nums.size())
{
return false;
}
int mid;
bool isFind;
//这里如果low = high,会造成mid相等,会陷入左边=中间=右边的死循环
if(low < high)
{
mid = low + (high - low ) / 2;
//找到了
if(nums.at(mid) == target)
{
return true;
}
//左半部分升序
if(nums.at(low) < nums.at(mid))
{
//如果在左半部分中
if(nums.at(low) <= target && target <= nums.at(mid))
{
return isFind = searchRotation(nums , target , low , mid);
}
else
{
return isFind = searchRotation(nums , target , mid + 1 , high);
}
}
//右半部分升序
else if(nums.at(low) > nums.at(mid))
{
if(nums.at(mid) <= target && target <= nums.at(high))
{
return isFind = searchRotation(nums , target , mid , high);
}
else
{
return isFind = searchRotation(nums , target , low , mid - 1);
}
}
//碰到左边等于中间
else
{
//如果左边不等于右边,左边到中间都是一样的,都不符合,右侧才有可能
if(nums.at(low) != nums.at(high))
{
return isFind = searchRotation(nums , target , mid + 1 , high);
}
//左边=中间=右侧,则左半部分或者右半部分都有可能,先查左边,找不到再查右边
else
{
isFind = searchRotation(nums , target , low , mid);
if(isFind)
{
return true;
}
//左边找不到,直接查右边
return isFind = searchRotation(nums , target , mid + 1 , high);
}
}
}
//这里low = high,只需要再找一次,因为当前元素还没有找过
if(nums.at(low) == target)
{
return true;
}
else
{
return false;
}
}
bool search(vector<int>& nums, int target) {
if(nums.empty())
{
return false;
}
bool isFind = searchRotation(nums , target , 0 , nums.size() - 1);
return isFind;
}
};
void process()
{
vector<int> nums;
int value;
int num;
Solution solution;
vector<int> result;
int target;
while(cin >> num >> target )
{
nums.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
nums.push_back(value);
}
bool isFind = solution.search(nums , target);
if(isFind)
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:81. Search in Rotated Sorted Array II
最新推荐文章于 2022-05-27 18:33:05 发布