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.
public class Solution { public int search(int[] nums, int target) { int index=0,len=nums.length; while(index<len-1 && nums[index]<=nums[index+1])index++; if(target>=nums[0] && target<=nums[index]){ return find(nums,0,index,target); }else{ return find(nums,index+1,len-1,target); } } private int find(int[] nums,int start,int end,int target){ if(start>end)return -1; int l=start,r=end,mid; while(l<=r){ mid=(l+r)/2; if(nums[mid]==target)return mid; else if(target<nums[mid])r=mid-1; else l=mid+1; } return -1; } }
int find(int* nums,int start,int end,int target){ int l=start,r=end,mid; if(start>end)return -1; while(l<=r){ mid=(l+r)>>1; if(nums[mid]==target)return mid; else if(nums[mid]>target)r=mid-1; else l=mid+1; } return -1; } int search(int* nums, int numsSize, int target) { int index=0; while(index<numsSize-1 && nums[index]<=nums[index+1])index++; if(target >= nums[0] && target<=nums[index]){ return find(nums,0,index,target); }else{ return find(nums,index+1,numsSize-1,target); } }
class Solution { public: int search(vector<int>& nums, int target) { int index=0,len=nums.size(); while(index<len-1 && nums[index]<=nums[index+1])index++; if(target>=nums[0] && target<=nums[index]){ return find(nums,0,index,target); }else{ return find(nums,index+1,len-1,target); } } private: int find(vector<int>& nums,int start,int end,int target){ if(start>end)return -1; int l=start,r=end,mid; while(l<=r){ mid=(l+r)>>1; if(nums[mid]==target)return mid; else if(nums[mid]>target)r=mid-1; else l=mid+1; } return -1; } };
class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer} def search(self, nums, target): index=0;length=len(nums) while index<length-1 and nums[index]<nums[index+1]:index+=1 if target>=nums[0] and target<=nums[index]:return self.find(nums,0,index,target) else:return self.find(nums,index+1,length-1,target) def find(self,nums,start,end,target): if start>end:return -1; l=start;r=end while l<=r: mid=(l+r)/2 if nums[mid]==target:return mid elif target>nums[mid]:l=mid+1 else:r=mid-1 return -1
LeetCode 33 Search in Rotated Sorted Array (C,C++,Java,Python)
原文地址:http://blog.csdn.net/runningtortoises/article/details/45725371