題目原文:
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
.
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
題意分析:
給出一個旋轉後的有序數組(可能有重複元素),給出某個值並找出其是否在數組中
要求時間複雜度爲O(log n),使用類二分查找的方式
首先可通過num[mid]與數組首尾元素的大小比較判斷出旋轉點的位置(考慮num[mid]與數組頭部元素相同的情況),再判斷target邊界的大小關係,進行邊界移動
解題代碼:
#include<iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool search(vector<int>& nums, int target) {
if (nums.size() == 0) return false;
int nMid = 0, nHead = 0, nTail = nums.size()-1;
while(nHead <= nTail)
{
nMid = (nHead+nTail)/2;
//cout<<"nmid is "<<nMid<<endl;
//cout<<"mid num is "<<nums[nMid]<<endl;
if (nums[nMid] == target)
return true;
if (nums[nMid] < nums[nHead] ) // mid 在後半區
{
if (target <nums[nMid] || target > nums[nTail])
{
nTail = nMid -1;
}
else
nHead = nMid+1;
}
else if(nums[nMid] > nums[nHead]) //mid在前半區
{
if (target > nums[nMid] || target < nums[nHead])
{
nHead = nMid+1;
}
else
nTail = nMid -1;
}
else // nums[nMid] == nums[nHead] && nums[nMid] != target
nHead = nHead +1;
}
return false;
}
};
//int main()
//{
// int a[8] = {4,5,6,7,8,1,2,3};
// vector<int> vec(a,a+8);
// int resout = Solution().search(vec,8);
// cout<<resout<<endl;
// system("pause");
// return 0;
//}