Suppose an array sorted in ascending order 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.
class Solution { public: int findMin(vector<int>& nums) { int start = 0, end = nums.size() - 1; while(start < end){ if(nums[start] < nums[end]) return nums[start]; int mid = start + (end - start)/2; if(nums[mid] >= nums[start]) start = mid + 1; else end = mid; } return nums[start]; } };
1.如果nums为空怎么办? 让编译器报错就足够了吗,需不需要其他操作
2.为什么
int mid = start + (end - start)/2;
相对 mid = (start + end)/2 可以避免overflow
答:因为start + end可能大于INT_MAX