题目描述:
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [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
题解:
本题的数组可分为两种情况,一种是前长后短,如:“[6,7,8,9,0,1,2]”,
另外一种情况是前短后长,如:[8,9,0,1,2,3,4]
package array; public class L33 { public static int search(int[] nums, int target) { return searchIndex2(nums,target,0,nums.length-1); } //针对于当前问题的查找算法 public static int searchIndex2(int[] nums, int target,int start,int end){ while(start <= end){ if(nums[(start+end)/2] == target){ return (start+end)/2; } if(nums[(start+end)/2] >= nums[start]){//前长后短的模式--情况1 if(nums[(start+end)/2] > target && (nums[start]<=target)){ //图中颜色加深区域 return searchIndex2(nums, target,start,(start+end)/2-1); }else { return searchIndex2(nums, target,(start+end)/2+1,end); } }else{//前短后长的模式情况2 if(nums[(start+end)/2] < target && (nums[end]>=target)){ //图中颜色加深区域 return searchIndex2(nums, target, (start+end)/2+1,end); }else { return searchIndex2(nums, target,start,(start+end)/2-1); } } } return -1; } //二分法查找的demo-本题没有用到 public static int searchIndex(int[] nums, int target,int start,int end){ while(start <= end){ if(nums[(start+end)/2] == target){ return (start+end)/2; }else if(nums[(start+end)/2] > target){ end = (start+end)/2-1; return searchIndex(nums, target,start,end); }else { start = (start+end)/2+; return searchIndex(nums, target,start,end); } } return -1; } public static void main(String[] args) { int[] nums = new int[]{4, 5, 6, 7, 0, 1, 2}; System.out.println(search(nums,0)); } }