Description: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.
Your algorithm’s runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
解题思路:题目的大概意思是,一个递增序列(不含重复数据)切成2半,前一半放到后面去组成新的序列,该序列有个特点,只有在分界点上递减,其他都是递增的。现在给定一个目标,找出该目标所在的位置,找不到返回-1。因为要求时间复杂度为O(log n),所有得使用二分法,当前数组可以使用二分法。如果mid的数据等于target,则立即返回mid。如果left到mid的数据是连续递增的,并且target在这个范围内,则在该范围内继续使用二分法,如果不在该范围内,则在mid到right使用二分法。如果left到mid数据不是连续递增的,说明在mid到right是连续递增的,如果target在mid到right范围内,则继续使用二分法,否则,在left到mid的范围内使用二分法。最后都找不到的话,返回-1。
参考代码:
int bin_search(int left, int right, vector<int> nums, int target) {
//递归用if
while (left <= right) {
int mid = (left + right) / 2;
if (target == nums[mid])
return mid;
if (nums[mid] >= nums[left] && target >= nums[left] && target < nums[mid]) {
//return bin_search(left, mid - 1, nums, target);
right = mid - 1;
}
else if (nums[mid] >= nums[left] && (target <= nums[left] || (target > nums[mid]))) {
//return bin_search(mid + 1, right, nums, target);
left = mid + 1;
}
else if (nums[mid] <= nums[left] && (target > nums[mid]) && target <= nums[right]) {
//return bin_search(mid + 1, right, nums, target);
left = mid + 1;
}
else {
//return bin_search(left, mid-1, nums, target);
right = mid - 1;
}
}
return -1;
}
int MySolution::search(vector<int>& nums, int target) {
return bin_search(0, nums.size() - 1, nums, target);
}
总结:最后发现递归和循环效率相差很大,这里给出测试结果
使用循环二分查找:
Runtime: 4 ms, faster than 81.73% of C++ online submissions for Search in Rotated Sorted Array.
Memory Usage: 8.9 MB, less than 43.37% of C++ online submissions for Search in Rotated Sorted Array.
使用递归二分查找:
Runtime: 8 ms, faster than 15.65% of C++ online submissions for Search in Rotated Sorted Array.
Memory Usage: 10.7 MB, less than 6.03% of C++ online submissions for Search in Rotated Sorted Array.