Find Minimum in Rotated Sorted Array leetcode

原题链接

直接贴代码,这道题是

search in rotated sorted array leetcode

的前面部分!

 1 class Solution {
 2 public:
 3     int findMin(vector<int>& nums) {
 4         if (nums.empty())
 5             return -1;
 6         int res = find(nums, 0, nums.size()-1);//好神奇,第二个参数无论减或者不减1,都不影响该题的结果
 7         if (res == -1)
 8             return -1;
 9         return nums[res];
10     }
11     int find(vector<int>& nums, int l, int r)
12     {
13         if (l>r || l >= nums.size())
14             return -1;
15         int mid = (l + r) / 2;
16         if (nums[l] <= nums[mid])
17         {
18             int pos = find(nums, mid + 1, r);
19             if (pos == -1)
20                 return l;
21             return nums[l]<nums[pos] ? l : pos;
22         }
23         else
24         {
25             int pos = find(nums, l, mid - 1);
26             if (pos == -1)
27                 return mid;
28             return nums[mid]<nums[pos] ? mid : pos;
29         }
30     }
31 };

 

你可能感兴趣的:(Find Minimum in Rotated Sorted Array leetcode)