Suppose an array sorted in ascending order 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.
/*
The sorted array is rotated. Then there must be two sorted sub arrays. When do the binary search, we should discuss the target is in which part.
For example, given [4,5,6,7,0,1,2], there are two sorted parts, [4,5,6,7] and [0,1,2]
If nums[mid] < target, there will be three conditions:
1. nums[mid] and target are both in [0,1,2]
2. nums[mid] and target are both in [4,5,6,7]
3. nums[mid] is in [0,1,2] and target is in [4,5,6,7]
Then when do the binary search, the search scope can be reduced by making left = mid in condition 1,2 or right = mid in condition 3.
It is similar when nums[mid] > target.
time:O(logn), space:O(1)
*/
public class Solution {public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int left = 0;
int right = nums.length - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
if (nums[mid] <= nums[right] &&
target > nums[right]) {
right = mid;
} else {
left = mid;
}
} else if (nums[mid] > target) {
if (nums[mid] > nums[right] &&
target <= nums[right]) {
left = mid;
} else {
right = mid;
}
} else {
return mid;
}
}
if (nums[left] == target) {
return left;
}
if (nums[right] == target) {
return right;
}
return -1;
}
}
No comments:
Post a Comment