字串演算法——旋轉陣列中查詢目標值(Search in Rotated Sorted Array)
阿新 • • 發佈:2019-02-07
問題:
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.
解決思路
class Solution {
public int search(int[] nums, int target) {
int len = nums.length;
if(len==0)return -1;
return dfs(nums,target,0,len-1);
}
private int dfs(int []nums,int target,int min,int max){
if(min>max){
return -1;
}
int mid = (min+max)/2;//中間索引
if(nums[mid] ==target)return mid;
if(nums[mid]>nums[min]){//中間索引左側是有序的
if(nums[mid]>target && nums[min]<target){//落在索引左側
return dfs(nums,target,min +1,mid-1);
}
if(nums[min] == target){
return min;
}
return dfs(nums,target,mid+1,max);//落在索引右側
}else {//索引右側是有序的
if(nums[mid]<target && nums[max]>target){//落在索引右側
return dfs(nums,target,mid+1,max-1);
}
if(nums[max] ==target){
return max;
}
return dfs(nums,target,min,mid-1);//落在索引左側
}
}
}