LeetCode:33 搜索旋转排序数组(二分搜索)
class Solution { public int binary_search(int[]nums,int left,int right,int target){ int mid=0; while(left<=right){ mid = (left+right)/2; if(nums[mid]>target){ right=mid-1; } else if(nums[mid]<target){ left=mid+1; } else{ return mid; } } if(nums[mid]!=target){ return -1; } else{ return mid; } } public int search(int[] nums, int target) { int n = nums.length; if(n==0){ return -1; } if(n==1){ return nums[0]==target?0:-1; } int mid=0; boolean flag=false; for(int i=1;i<n;i++){ if(nums[i-1]>nums[i]){ mid = i-1; flag=true; break; } } if(flag==false){ mid=n-1; } if(target>=nums[0]&&target<=nums[mid]){ return binary_search(nums,0,mid,target); } else{ return binary_search(nums,mid+1,n-1,target); } } }