class Solution { public: int findPeakElement(vector<int>& nums) { int n = nums.size(); if (n == 1) { return 0; } if (nums[0] > nums[1]) { return 0; } if (nums[n - 2] < nums[n - 1]) { return n - 1; } for (int i = 1; i < nums.size() - 1; i++) { if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) { return i; } } } };
补充一个python的实现,使用二分查找:
1 class Solution: 2 def findPeakElement(self, nums: List[int]) -> int: 3 l, r = 0, len(nums) - 1; 4 while l < r: 5 m = l + (r - l) // 2 6 if nums[m] > nums[m + 1]: 7 r = m 8 elif nums[m] < nums[m + 1]: 9 l = m + 1 10 return l