文章目录
- 寻找峰值
- 寻找旋转数组最小值
寻找峰值
class Solution {
public:int findPeakElement(vector<int>& nums) {int left = 0, right = nums.size() - 1;while(left < right){int mid = left + (right - left) / 2;if(nums[mid] < nums[mid + 1])left = mid + 1;elseright = mid;}return left;}
};
寻找旋转数组最小值
本质和上篇最后一题一样,只是上个题找峰顶,该题找谷底;
A、D两点都可作为基准点,但A点设计边界问题
/*D为基准点*/
class Solution {
public:int findMin(vector<int>& nums) {int left = 0, right = nums.size() - 1;int T = nums[right];while(left < right){int mid = left + (right - left) / 2;if(nums[mid] < T)right = mid;elseleft = mid + 1;}return nums[left];}
};
/*A为基准点*/
class Solution {
public:int findMin(vector<int>& nums) {int left = 0, right = nums.size() - 1;int T = nums[0];// 排除原数组if(T < nums[right]) return T;if(right == 1) return nums[right];while(left < right){int mid = left + (right - left) / 2;if(nums[mid] >= T)left = mid + 1;elseright = mid;}return nums[left];}
};