本文主要是介绍Leecode 162. Find Peak Element,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
可运行
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);}};
这篇关于Leecode 162. Find Peak Element的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!