首页 > 其他 > 详细

162. Find Peak Element

时间:2018-02-09 13:56:02      阅读:164      评论:0      收藏:0      [点我收藏+]

题目

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!