leetcode162 Find Peak Element
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode162 Find Peak Element相关的知识,希望对你有一定的参考价值。
1 """ 2 A peak element is an element that is greater than its neighbors. 3 Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. 4 The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. 5 You may imagine that nums[-1] = nums[n] = -∞. 6 Example 1: 7 Input: nums = [1,2,3,1] 8 Output: 2 9 Explanation: 3 is a peak element and your function should return the index number 2. 10 Example 2: 11 Input: nums = [1,2,1,3,5,6,4] 12 Output: 1 or 5 13 Explanation: Your function can return either index number 1 where the peak element is 2, 14 or index number 5 where the peak element is 6. 15 """ 16 class Solution: 17 def findPeakElement(self, nums): 18 if len(nums) <= 1: 19 return 0 20 nums.append(-float(‘inf‘))#针对[1, 2] [1, 2, 3] 这种递增序列的情况 21 i = 1 22 while i < len(nums): 23 if nums[i-1] < nums[i] and nums[i] > nums[i+1]: 24 return i 25 i += 1 26 return 0 27 if __name__ == ‘__main__‘: 28 ans = Solution() 29 nums = [1, 2, 3, 1] 30 print(ans.findPeakElement(nums))
以上是关于leetcode162 Find Peak Element的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 162 Find Peak Element(二分法)
刷题-LeetCode162 Find Peak Element
LeetCode 162. Find Peak Element 20170706