zoukankan      html  css  js  c++  java
  • 【leetcode刷题笔记】Find Peak Element

    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.


    题解:题目要求用O(logn)的时间复杂度找到局部最大值,很容易想到二分算法。设置一个函数 private boolean findPeakHelper(int[] num,int begin,int end){ ,每次判断(begin+end)/2位置上的元素是否满足要求,如果不满足就搜索左半边数组,如果在左半边搜索到了,右半边就没有必要搜索了,因为题目只让返回一个解;如果左半边没搜索到,就继续递归搜索右半边。特别注意对位置0和位置n-1处元素的处理。

    JAVA版本代码如下:

     1 public class Solution {
     2     int index = 0;
     3     public int findPeakElement(int[] num) {
     4         findPeakHelper(num, 0, num.length-1);
     5         return index;
     6     }
     7     private boolean findPeakHelper(int[] num,int begin,int end){
     8         if(begin > end)
     9             return false;
    10         int mid = (begin + end)/2;
    11         if(mid == 0)
    12         {
    13             if(mid+1 < num.length && num[mid+1] < num[mid]){
    14                 index = mid;
    15                 return true;
    16             }else {
    17                 return findPeakHelper(num, mid+1, end);
    18             }
    19         }
    20         
    21         if(mid-1 >= 0 && mid == num.length-1){
    22             if(num[mid-1] < num[mid]){
    23                 index = mid;
    24                 return true;
    25             }else{
    26                 return findPeakHelper(num, begin, mid-1);
    27             }
    28         }
    29         
    30         if(num[mid-1] < num[mid] && num[mid+1] < num[mid]){
    31             index = mid;
    32             return true;
    33         }
    34         
    35         if(findPeakHelper(num, begin, mid-1))
    36             return true;
    37         else {
    38             return findPeakHelper(num, mid+1, end);
    39         }
    40     }
    41 }
  • 相关阅读:
    2020.08.28【周报】
    区间合并【排序、栈】
    1042 数字0-9的数量【解题数分DP】
    asp.net数据分页方法
    纯css面板插件,自适应,多样式
    c#winform图表控件使用示例
    使用妹子UI开发的体验分享
    阿里云储存代码整理(由三卷天书整理)
    测试程序的时候用到写参数或者错误日志的几个方法,用来方便发现错误
    fineUI表格控件各属性说明
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/4387336.html
Copyright © 2011-2022 走看看