Find Min In Rotated Sorted Array2,包含重复数字的反转序列找最小值。

 1 public int findMin(int[] nums)
 2     {
 3         return findMin(nums, 0, nums.length - 1);
 4     }
 5     public int findMin(int[] nums, int left, int right)
 6     {
 7         int mid = (left + right)/2;
 8         if(left == right)
 9         {
10             return nums[left];
11         }
12         if(nums[left] < nums[right])
13         {
14             return nums[left];
15         }
16         if((left - right) == 1)//这一步必须要有,因为会涉及到left+1,right-1,例如序列为11.
17         {
18             return Math.min(nums[left], nums[right]);
19         }
20         if(nums[left] == nums[mid] && nums[mid] == nums[right])
21         {
22             return findMin(nums, left + 1, right - 1);
23         }
24         else if(nums[left] <= nums[mid])
25         {
26             return findMin(nums, mid+1, right);
27         }
28         else
29         {
30             return findMin(nums, left, mid);
31         }
32     }
33     //迭代方法
34     public int findMin2(int[] nums, int left, int right)
35     {
36         while(left <= right)
37         {
38             int mid = (left + right)/2;
39             if(left == right)
40             {
41                 return nums[left];
42             }
43             if(nums[left] < nums[right])
44             {
45                 return nums[left];
46             }
47             if(nums[right] == nums[mid] && nums[mid] == nums[right])
48             {
49                 left ++;
50                 right --;
51             }
52             else if(nums[left] <= nums[mid])
53             {
54                 left = mid + 1;
55             }
56             else
57             {
58                 right = mid;
59             }
60         }
61         return nums[left];
62     }

 

posted @ 2016-06-09 15:39  32ddd  阅读(192)  评论(0编辑  收藏  举报