[leedcode 33] Search in Rotated Sorted Array
Suppose a sorted array 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.
public class Solution { public int search(int[] nums, int target) { //二分查找法的变形,利用数组特点,每次切掉一半 //注意比较时等号的使用,以及比较的条件if(target>=nums[left]&&target<nums[mid]) //本题还可以利用递归进行解决,递归貌似没有利用数组的特点,所有二分法都通用 /* if(nums.length<1) return -1; int left=0; int right=nums.length-1; while(left<=right){ if(left==right) return nums[left]==target?left:-1; int mid=(left+right)/2; if(nums[mid]==target){ return mid; } if(nums[mid]>=nums[left]){//注意等号 if(target>=nums[left]&&target<nums[mid])//注意等号 right=mid-1; else{ left=mid+1; } }else{ if(target>nums[mid]&&target<=nums[right]){//注意等号 left=mid+1; }else{ right=mid-1; } } } return -1;*/ //if(nums.length<1)return -1; return find(nums,target,0,nums.length-1); } public int find(int []num,int target,int start,int end){ if(start>end) return -1; int mid=(start+end)/2; if(num[mid]==target) return mid; int res=find(num,target,start,mid-1); if(res==-1) //若果左侧没有找到,进行右侧的查找 res=find(num,target,mid+1,end); return res; } }