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

2014-03-05 09:15:45

#### Search in Rotated Sorted Array II -- LeetCode

2014-03-06 02:04:55

#### 【LEETCODE】33-Search in Rotated Sorted Array [Python]

2016-01-22 11:26:41

#### 【LeetCode】Search in Rotated Sorted Array 解题报告

2014-10-25 17:00:36

#### leetcode 81. Search in Rotated Sorted Array II-旋转数组|二分查找

2016-06-07 11:34:23

#### [LeetCode]81.Search in Rotated Sorted Array II

2014-01-15 22:29:05

#### LeetCode 33 Search in Rotated Sorted Array（在旋转排序数组中搜索）（*）

2015-11-26 18:50:31

#### 33.Search in Rotated Sorted Array

2015-03-17 10:38:25

#### Leetcode: Search in Rotated Sorted Array II

2013-10-04 22:15:27

#### Find Minimum in Rotated Sorted Array II -- LeetCode

2014-10-25 07:12:45