Subject description:
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). Find the minimum element. You may assume no duplicate exists in the array.
There are original title directly on the code on this question "to prove safety offer"
solution:
int findMin(vector<int>& nums) { int start = 0; int end = nums.size() - 1; while (start < end) { if (nums[start] < nums[end]) break; int mid = start + (end - start) / 2; if (nums[mid] >= nums[start]) start = mid + 1; else end = mid; } return nums[start]; }
Reference: https://leetcode.com/discuss/13389/compact-and-clean-c-solution
The above-described procedure does not consider the presence of the same element of the array. If we consider, then, the code needs to be modified.
solution:
int findMin(vector<int>& nums) { int start = 0; int end = nums.size() - 1; while (start < end) { if (nums[start] < nums[end]) break; int mid = start + (end - start) / 2; if (nums[mid] > nums[end]) start = mid + 1; else if (nums[mid] < nums[end]) end = mid; else { ++start; --end; } } return nums[start]; }
Finally, attach a solution on "to prove safety offer":
int MinInOrder(vector<int> &nums, int start, int end) { int min = nums[start]; for (int i = 1; i < nums.size(); ++i) { if (nums[i] < min) min = nums[i]; } Return min; } int findMin(vector<int>& nums) { int start = 0; int end = nums.size() - 1; while (start < end) { if (nums[start] < nums[end]) break; int mid = start + (end - start) / 2; if (nums[mid] == nums[start] && nums[mid] == nums[end]) { return MinInOrder(nums, start, end); } if (nums[mid] >= nums[start]) start = mid + 1; else end = mid; } return nums[start]; }
PS:
Solution on the "wins the offer" is not necessarily the best! ! !
Reproduced in: https: //www.cnblogs.com/gattaca/p/4643750.html