81 Search in Rotated Array
Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
http://articles.leetcode.com/searching-element-in-rotated-array
Trick:
1 Rather than find the pivot of the rotated sorted array, use the midpoint to compare the most left/right element, and determine which side next to the midpoint is sorted.
public int search(int[] nums, int target) { int left= 0; int right = nums.length-1;
while(left<=right)
{
//The mid point is changing every partition
int mid = left + ((right-left)/2);
if(nums[mid] == target)
{
return mid;
}
if(nums[left]<=nums[mid])
{
if(nums[left]<=target && target<nums[mid])
{
right = mid-1;
}
else
{
left = mid+1;
}
}
else
{
if(nums[mid] <target && target<= nums[right])
{
left = mid+1;
}
else
{
right=mid-1;
}
}
}
return -1;
}