Title: http://oj.leetcode.com/problems/search-in-rotated-sorted-array/
Suppose a sorted array is rotated in some pivot unknown to your beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are 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.
Title translation:
Suppose an ordered array rotates in an unknown position.
(i.e. 0 1 2 4 5 6 7 May become 4 5 6 7 0 1 of 2).
Searches for a given target value. Returns the index of the array if it exists, or returns-1.
You can assume that there are no duplicate elements in the array.
Analysis:
Similar to a binary lookup, but it is more complicated to determine which child interval to be in.
C + + implementation:
Class Solution {public
:
int search (int a[], int n, int target) {
int left = 0;
int right = n-1;
While [left <= right]
{
int mid = (left + right)/2;
if (a[mid] = = target)
{return
mid;
}
if (A[mid] >= A[left])
{
if (A[mid] > Target && a[left] <= target)
{right
= mid-1;
}
Else
{left
= mid + 1;
}
}
else
{
if (A[mid] < target && A[right] >= target)
{left
= mid + 1;
}
else
{Right
= mid-1
}}} return-1;
}
;
Java implementation:
public class Solution {public
int search (int[] A, int target) {
int left = 0;
int right = A.length-1;
While [left <= right] {
int mid = (left + right)/2;
if (a[mid] = = target) {return
mid;
}
if (A[mid] >= A[left]) {
if (A[mid] > Target && a[left] <= target) {right
= mid-1;
} els e {Left
= mid + 1;
}
} else {
if (A[mid] < target && A[right] >= target) {left
= Mid + 1;
} else {Right
= mid-1
}}} Return-1
}
}
Python implementations:
Class Solution:
# @param A, a list of integers
# @param target, an integer to is searched
# @return an integer
def search (self, A, target): Left
= 0 Right
= Len (A)-1 while left
<= right:
mid = (left + right) /2
if a[mid] = = target: Return
mid
if A[mid] >= A[left]:
if A[MID] > Target and a[left] <= ta Rget: Right
= mid-1
else: Left
= mid + 1
else:
if A[MID] < target and A[right] >= target: Left
= mid + 1
else: Right
= mid-1
return-1
Thank you for reading and welcome comments.