标签:
Question:
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.
Solution:
1 class Solution { 2 public: 3 int search(vector<int>& nums, int target) { 4 int left=0; 5 int right=nums.size()-1; 6 if(left==right && nums[left]==target) 7 return left; 8 while(left!=right) 9 { 10 int mid=(left+right)/2; 11 if(nums[mid]==target) return mid; 12 if(nums[left]<=nums[mid]) 13 { 14 if(nums[left]<=target && target<=nums[mid]) 15 right=mid; 16 else 17 left=mid+1; 18 } 19 else 20 { 21 if(nums[mid]<=target && target<=nums[right]) 22 left=mid+1; 23 else 24 right=mid; 25 } 26 if(left==right && nums[left]==target) 27 return left; 28 } 29 return -1; 30 31 } 32 };
Search in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/riden/p/4631415.html