标签:space value vector oat exists ase stream class code
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.





1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Solution {public: int search(vector<int>& nums, int target) { int l = 0, r = nums.size() - 1, m, result = -1; while(l <= r){ m = (l + r) >> 1; if(nums[m] == target) return m; if(nums[l] <= nums[m])// indicate that the nums[m] is in the ascending order part { if( nums[l] <= target && nums[m] > target){// target is in [l,m) r = m - 1; } else{ //target is in [m,R) l = m + 1; } } else{ if(nums[m] < target && nums[r] >= target){ //target is in (m,r] l = m + 1; } else{// target is in [l,m) r = m - 1; } } }//end of while return -1; }}; |
33. Search in Rotated Sorted Array
标签:space value vector oat exists ase stream class code
原文地址:http://www.cnblogs.com/zhxshseu/p/a2412c8ec0df3ca09ffcd24487101339.html