题目:
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6]might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
思路:
首先需要找到数组中两个递增的序列,以 [2,5,6,0,0,1,2]为例。首先要找到6的位置这样就相当于把数组分为[2,5,6]和[0,0,1,2]两部分呢。
之后对两部分分别进行二叉查找。返回结果。
代码:
public boolean search(int[] nums, int target) {
boolean flag = false;
if(nums == null || nums.length == 0)
return flag;
int pivot = 0;
for(int i=0;i<nums.length - 1;i++){
if(nums[i] > nums[i+1]){
pivot = i;
break;
}
}
return binarySearch(nums, 0, pivot, target) || binarySearch(nums, pivot + 1, nums.length - 1, target);
}
/**
* Binary search to find target.
* @param nums
* @param left
* @param right
* @param target
* @return
*/
private boolean binarySearch(int [] nums, int left, int right, int target){
int begin = left;
int end = right;
while(begin <= end){
int mid = (begin + end)/2;
if(nums[mid] == target)
return true;
if(nums[mid] < target)
begin = mid + 1;
else
end = mid - 1;
}
return false;
}
网友评论