标签:
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 len = nums.length; int leftMin = nums[0]; int rightMax = nums[len - 1]; if (target > rightMax && target < leftMin) return -1; boolean targetAtLeft = target >= leftMin; int left = 0; int right = len - 1; while (left <= right) { int mid = (left + right) / 2; int midVal = nums[mid]; if (midVal == target) return mid; if (targetAtLeft) { if (midVal >= leftMin && midVal < target) left = mid + 1; // go right else right = mid - 1; //go left } else { if (midVal <= rightMax && midVal > target) right = mid - 1; // go left else left = mid + 1; //go right } } return -1; } }
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.
33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II &&
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5700052.html