码迷,mamicode.com
首页 > 其他好文 > 详细

162. Find Peak Element

时间:2018-02-09 15:18:01      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:else   for   fun   blog   element   func   说明   lis   def   

题目

A peak element is an element that is greater than its neighbors.

Given an input array wherenum[i] ≠ num[i+1], find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

这个题目需要说明的是,该数组里的值,有3中情况:

  • 单增
  • 单减
  • 先增,后减

扫描数组

如果nums[i]>nums[i-1] and nums[i] > nums[max], 则 max = i

class Solution(object):
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max = 0
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1] and nums[i] > nums[max]:
                max = i
        return max

这段代码还是有其他改进的地方。

二分法

基础的代码在这儿,肯定不合适,需要对其进行修改。

class Solution(object):
    def findPeakElement2(self, nums):
        l, r = 0, len(nums) - 1
        while l < r:
            mid = l + (r - l) // 2
            if nums[mid] > nums[mid + 1]:
                r = mid
            else:
                l = mid + 1
        return l

162. Find Peak Element

标签:else   for   fun   blog   element   func   说明   lis   def   

原文地址:https://www.cnblogs.com/yuanoung/p/8434800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!