leetcode腾讯精选练习50(15)——搜索旋转排序数组
题目描述
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法思路
二分法找到旋转的位置,再二分找到target的位置。
代码
class Solution{
int[] nums;
int target;
public int findRotatedIndex(int left,int right){
if(nums[left]<nums[right]) return 0; //全部翻转,翻转位置为0
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]>nums[mid+1]){
return mid+1; //mid处为最大值,即在此翻转
}else{
if(nums[mid]<nums[left]){ //如果nums[mid]<nums[left],则翻转处在左半部
right = mid-1;
}else{
left= mid + 1;
}
}
}
return 0;
}
public int search(int left,int right){
while(left<=right){
int t = (left+right)/2;
if(nums[t] == target)
return t;
else{
if(target<nums[t]){
right = t-1;
}else{
left = t+1;
}
}
}
return -1;
}
public int search (int[] nums,int target){
this.nums = nums;
this.target = target;
int len = nums.length;
if(len == 0){
return -1;
}
if(len == 1){
return this.nums[0]==this.target ? 0:-1;
}
int index = findRotatedIndex(0,len-1);
if(nums[index] == target)
return index;
if(index == 0)
return search(0,len-1);
if(target<nums[0]){
return search(index,len-1);
}else{
return search(0,index);
}
}
}