目錄
1,題目描述
英文描述:
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
中文描述:
假設按照升序排序的數組在預先未知的某個點上進行了旋轉。
( 例如,數組 [0,1,2,4,5,6,7] 可能變爲 [4,5,6,7,0,1,2] )。
搜索一個給定的目標值,如果數組中存在這個目標值,則返回它的索引,否則返回 -1 。
你可以假設數組中不存在重複的元素。
你的算法時間複雜度必須是 O(log n) 級別。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2,思路
- 因爲只繞着一個點(哨兵)進行旋轉,所以有比較特殊的性質;
- 題目限定時間複雜度爲O(logn),明顯是應用二分法;
- 對任意left和right,mid只有兩種位置:哨兵的左邊、哨兵的右邊。判斷是哪一種,只需要將nums[0]與nums[mid]比較即可;
二分法的本質是給左右指針賦值,所以找出左右指針更新的條件即可。由於要麼左指針右移,要麼右指針左移,所以只需要找出一種情況即可,這裏找的是右指針左移的情況:
- mid位於哨兵左邊時,有一種情況右指針需要左移(right=mid):
- mid位於哨兵右邊時,有兩種情況右指針需要左移:
3,AC代碼
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1, mid;
while(left < right){
mid = (left + right) / 2;
if((nums[0] <= target && target <= nums[mid]) ||
(nums[0] > nums[mid] && (target <= nums[mid] || target >= nums[0]))){
right = mid;
}
else left = mid + 1;
}
return left == right && nums[left] == target ? left : -1;
}
};
4,參考測試結果