Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  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.  
  6. Example 1:
  7.  
  8. Input: nums = [1,2,3,1]
  9. Output: 2
  10. Explanation: 3 is a peak element and your function should return the index number 2.
  11.  
  12. Example 2:
  13.  
  14. Input: nums = [1,2,1,3,5,6,4]
  15. Output: 1 or 5
  16. Explanation: Your function can return either index number 1 where the peak element is 2,
  17.             or index number 5 where the peak element is 6.
  18. '''
  19. class Solution(object):
  20.     def findPeakElement(self, nums):
  21.         """
  22.        :type nums: List[int]
  23.        :rtype: int
  24.        """
  25.        
  26.         left = 0
  27.         right = len(nums) - 1
  28.        
  29.         while left < right:
  30.             mid = left + right // 2
  31.            
  32.             if nums[mid] > nums[mid + 1]:
  33.                 right = mid
  34.             else:
  35.                 left = mid + 1
  36.            
  37.         return left
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement