# 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.

Subscribe to see which companies asked this question
**

#### C++

class Solution {
public:
int search(vector<int>& nums, int target) {
int first = 0;
int last = nums.size();
while(first != last)
{
const int mid = first + (last - first) / 2;
if(nums[mid] == target)
return mid;
if(nums[first] <= nums[mid])
{
if(nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
}
else
{
if(nums[last-1] >= target && target > nums[mid])
first = mid + 1;
else
last = mid;
}
}
return -1;
}
};

#### Java

public class Solution {
public int search(int[] nums, int target) {
int first = 0;
int last = nums.length;

while(first != last)
{
int mid = first + (last - first) / 2;
if(nums[mid] == target)
return mid;
if(nums[first] <= nums[mid])
{
if(nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
}
else
{
if(nums[last-1] >= target && target > nums[mid])
first = mid  + 1;
else
last = mid;
}
}
return -1;
}
}

#### Python

class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
first = 0
last = len(nums)
while(first != last):
mid = first + (last - first) / 2;
if(nums[mid] == target):
return mid
if(nums[mid] >= nums[first]):
if(nums[first] <= target and target < nums[mid]):
last = mid
else:
first = mid + 1
else:
if(nums[mid] < target and target <= nums[last-1]):
first = mid + 1
else:
last = mid
return -1

• 本文已收录于以下专栏：

举报原因： 您举报文章：Search in Rotated Sorted Array 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)