zoukankan      html  css  js  c++  java
  • leetcode------Find Peak Element

    标题: Find Peak Element
    通过率: 32.3%
    难度: 中等

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

    Given an input array where num[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.

    click to show spoilers.

    Note:

    Your solution should be in logarithmic complexity.

     本题思路确实比较清楚,但是想起来不容易,要充分看到给定的条件:

    1、不存在相邻相等的元素,

    2、默认位置为-1和n的元素的值为负无穷,

    这两个条件意思是,不用去考虑相等元素。由于可能存在多个peak值,只用找到该数组中元素最大值即可,然后就是第0个位置和最后一个元素也再考虑范围内,不用单独考虑。

    整体思路就是二分法查找,在处理mid时比较下mid与mid+1的关系,看是否是递增还是递减。

    java代码如下:

     1 public class Solution {
     2     public int findPeakElement(int[] num) {
     3         int start=0,end=num.length-1,mid=0,mid1=0;
     4         while(start<end){
     5             mid=(start+end)/2;
     6             mid1=mid+1;
     7             if(num[mid]<num[mid1]) start=mid1;
     8             else end=mid;
     9         }
    10         return start;
    11     }
    12 }

    2、python:

     1 class Solution:
     2     # @param num, a list of integer
     3     # @return an integer
     4 
     5     def findPeakElement(self, num):
     6         n = len(num)
     7         left, right = 0, len(num) - 1
     8         while left < right:
     9             mid = (left + right) >> 1
    10             if (mid == 0 or num[mid] > num[mid - 1]) and (mid == n - 1 or num[mid] > num[mid + 1]):
    11                 return mid
    12             if mid > 0 and num[mid - 1] > num[mid]:
    13                 right = mid - 1
    14             else:
    15                 left = mid + 1
    16         return left
  • 相关阅读:
    MeshLab编译理解
    几个经典的数学库之一学习---VCGlib(1)
    开源协议的几种类型认识
    Win & Mac 系统之间U盘传递的U盘文件格式选取问题
    用VS2010编译python2.7的源码
    类之间关系理解:组合>聚合>关联>依赖;实现,继承
    Linux进阶:让效率翻倍的Bash技巧(一)
    Linux下nc命来实现文件传输
    nginx 405 not allowed问题的解决
    vim同时打开多个文件进行编辑
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4283391.html
Copyright © 2011-2022 走看看