• 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))
  • 相关阅读:
    10.30 afternoon
    10.29 afternoon
    10.29 morning

    10.27 noip模拟试题
    codevs 3052 多米诺 二分图匹配
    poj 1849 Two
    10.26 noip模拟试题
    10.25 noip模拟试题
    .NET Core EF 版本问题
  • 原文地址:https://www.cnblogs.com/yawenw/p/12494360.html
Copyright © 2020-2023  润新知