算法系列—— Find Peak Element

来源:互联网 发布:java发送邮件 多邮箱 编辑:程序博客网 时间:2024/06/05 18:14

题目描述

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.

解题思路

顺序查找法

顺序遍历数组。本题的一个重要特点是,从第一个元素开始,若其大于相邻的后续元素,则第一个元素就是一个局部最大值,返回即可。若其小于相邻的后续元素,则第二个元素大于第一个元素。如此,一一遍历数组,第一次出现,第i个元素若大于其相邻后续元素,则该元素就是一个局部最大值,返回即可。
时间复杂度为O(n)

二分查找法

如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧(不包含)必包含一个局部最大值。
平均时间复杂度为O(logn)

程序实现

顺序查找

public class Solution {    public int findPeakElement(int[] nums) {       for(int i=1;i<nums.length;i++){           if(nums[i-1]>nums[i])           return i-1;       }      return nums.length-1;    }}

二分查找

public class Solution {    public int findPeakElement(int[] nums) {         int left=0,right=nums.length-1;          while(left<right){              int mid=(left+right)/2;              if(nums[mid]<nums[mid+1])                  left=mid+1;              else                  right=mid;          }          return left;    }}
原创粉丝点击