classSolution { intgetOrDefault(vector<int>& nums, int i, int def = INT_MIN){ if(i < 0or i >= nums.size()) return def; return nums[i]; } public: intfindPeakElement(vector<int>& nums){ int l = 0, r = nums.size() - 1; while(l < r) { int m = l + (r - l) / 2; int left = getOrDefault(nums, m - 1); int right = getOrDefault(nums, m + 1); if(nums[m] > left and nums[m] > right) return m; elseif(left > right) r = m - 1; else l = m + 1; } return l; } };
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intfindPeakElement(vector<int>& nums){ intl(0), r(nums.size() - 1); while(l < r) { int m = (l + r) / 2; if(nums[m] > nums[m + 1]) r = m; else l = m + 1; } return l; } };