可运行
class Solution {
public:
int findPeakElement(vector<int>& nums) {
return findPeakElementCore(nums, 0, nums.size() - 1);
}
private:
int findPeakElementCore(vector<int>& nums, int beg, int end) {
if (end == beg) return beg;
if (end - beg == 1){
if(nums[end] < nums[beg]) return beg;
else return end;
}
int mid = beg + (end - beg) / 2;
if (nums[mid] > nums[beg] && nums[mid] > nums[end]) {
if (nums[mid] < nums[mid + 1]) return findPeakElementCore(nums, mid + 1, end);
else return findPeakElementCore(nums, beg, mid);
}
if (nums[beg] > nums[beg + 1]) {
return beg;
}
if (nums[end] > nums[end - 1]) {
return end;
}
return findPeakElementCore(nums, beg + 1, end - 1);
}
};
参考后
class Solution {
public:
int findPeakElement(vector<int>& nums) {
return findPeakElementCore(nums, 0, nums.size() - 1);
}
private:
int findPeakElementCore(vector<int>& nums, int beg, int end) {
if (end == beg) return beg;
int mid = beg + (end - beg) / 2;
if (nums[mid] < nums[mid + 1]) return findPeakElementCore(nums, mid + 1, end);
return findPeakElementCore(nums, beg, mid);
}
};