LeetCodeHot100_33——《搜索旋转排序数组》
读题思路:感觉在有序里边找target,还要O(log n)的都可以想到二分法。这道题的意思感觉就是将数组分成两个都是有序的部分,然后分别看target在哪部分,然后就可以了。
具体代码:
int search(vector<int>& nums, int target) {
int n = nums.size();
if (n==0){ return -1; }
if (n==1)
{
return nums[0] == target ? 0 : -1;
}
int left = 0, right = n - 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (nums[mid]==target){ return mid; }
if (nums[0] <= nums[mid])
{
if (target >= nums[0] && target < nums[mid]) { right = mid - 1; }
else{ left = mid + 1; }
}
else
{
if (nums[mid] < target && target <= nums[n - 1]) { left = mid + 1; }
else { right = mid - 1; }
}
}
return -1;
}