33. 搜索旋转排序数组-LeetCode

心得:开始的做法是用数组下标映射,找到按序的数组的下标,

然后二分,看到别人的题解用的是直接二分判断,感觉比我的简单

而且不容易错。

自己的代码:

 1 class Solution {
 2    public int search(int[] nums, int target) {
 3             if(nums==null||nums.length==0)
 4                 return -1;
 5             int index=0;
 6             for(int i=0;i<nums.length-1;i++)
 7             {
 8                 if(nums[i]>nums[i+1])
 9                 {
10                      index=nums.length-i-1;
11                      break;
12                 }
13             }
14             return binaryFind(nums,target,index,0,nums.length-1);
15         }
16     public int  binaryFind(int[] nums,int target,int index,int left,int right)
17     {
18         int center=(left+right)>>>1;
19         int realCenter=center<index?center+nums.length-index:center-index;
20         int realLeft=left<index?left+nums.length-index:left-index;
21         int realRight=right<index?right+nums.length-index:right-index;        
22         if(left<=right)
23         {
24             if(nums[realCenter]==target)
25               return realCenter;
26             else if(nums[realCenter]<target)
27                 return binaryFind(nums,target,index,center+1,right);
28             else if(nums[realCenter]>target)
29                 return binaryFind(nums,target,index,left,center-1);
30         }
31         else
32         {
33         return -1;
34         }
35         return 0;
36     }
37 }

猜你喜欢

转载自www.cnblogs.com/pc-m/p/10914124.html
今日推荐