19.2.2 [LeetCode 33] Search in Rotated Sorted Array
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
题意
有序数组截成两段打乱顺序(或者也可能保持原序),以logn的复杂度找数
题解
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int search(vector<int>& nums, int target) { 4 if (nums.size() <= 0)return -1; 5 int pivot = nums[0], size = nums.size(), mididx = size, s=0, e=size-1; 6 if (nums[size - 1] <= pivot) { 7 int S = 0,E = size - 1; 8 while (S <= E) { 9 int mid = (S + E) / 2; 10 if (nums[mid] >= pivot) 11 S = mid + 1; 12 else 13 E = mid - 1; 14 } 15 mididx = S; 16 if (mididx > size - 1) 17 mididx = 0; 18 if (nums[size - 1] >= target) { 19 s = mididx, e = max(size - 1,s); 20 } 21 else 22 s = 0, e = max(mididx - 1,s); 23 } 24 while (s < e) { 25 int mid = (s + e) / 2; 26 if (nums[mid] < target) 27 s = mid + 1; 28 else 29 e = mid; 30 } 31 if (s >= size)return -1; 32 if (nums[s] == target) 33 return s; 34 return -1; 35 } 36 };
先找从哪开始是分界点,然后再找数
注定失败的战争,也要拼尽全力去打赢它;
就算输,也要输得足够漂亮。