Search in Rotated Sorted Array
Posted cccv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Search in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。
Suppose a sorted array 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.
1 int Solution::search(const vector<int>& nums, int target) 2 { 3 // 解题思路:当nums[mid] > nums[last-1]时, 4 // [first,mid]有序,[mid,last)无序, 5 // 否则[first,mid]无序,[mid,last)有序, 6 // 因为当 nums[mid] > target 时,target 可能在mid的左边或者右边, 7 // 所以还要将target 与 nums[first]对比 8 int first = 0, last = nums.size(); 9 while(first != last) 10 { 11 const int mid = first + (last - first) / 2; 12 if(nums[mid] == target) 13 return mid; 14 if(nums[mid] > nums[last-1]) 15 { 16 if(nums[mid] > target && target >= nums[first]) 17 last = mid; 18 else 19 first = mid + 1; 20 } else 21 { 22 if(nums[mid] < target && target <= nums[last-1]) 23 first = mid + 1; 24 else 25 last = mid; 26 } 27 } 28 return -1; 29 }
以上是关于Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
Search in Rotated Sorted Array
33. Search in Rotated Sorted Array
33. Search in Rotated Sorted Array
33. Search in Rotated Sorted Array