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.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1
这个题目的意思是在一个逆转的数组中进行二分查找,使用的方法为虚拟节点(类似于一致性哈希中的虚拟节点),将虚拟节点映射到真实节点即可。
1)虚拟节点法
class Solution {
public int search(int[] nums, int target) {
int n = nums.length;
int low = 0 , high = n - 1;
while(low < high){//设置虚拟节点
int mid = (low + high) / 2;
if(nums[mid] > nums[high]){
low = mid + 1;
}else{
high = mid;
}
}
int rot = low;
low = 0;
high = n - 1;
while(low <= high){
int mid = (low + high) / 2;
int real = (mid + rot) % n;//虚拟节点映射到真实的节点。
if(nums[real] == target){
return real;
}else if(nums[real] < target){
low = mid + 1;
}else{
high = mid - 1;
}
}
return -1;
}
}
2)
class Solution {
public int search(int[] nums, int target) {
int l=0;
int h=nums.length-1;
while(l<=h){
int mid=(l+h)/2;
int midValue=(nums[mid]<nums[0])==(target<nums[0])?nums[mid]:target<nums[0]?Integer.MIN_VALUE:Integer.MAX_VALUE;
if(target==midValue){
return mid;
}else if(target>midValue){
l=mid+1;
}else{
h=mid-1;
}
}
return -1;
}
}