Find Peak Element

来源:互联网 发布:根据域名查询服务器 编辑:程序博客网 时间:2024/05/22 10:43

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.


思路:题意是要求找出第一个局部最大值得下标。由于两端 num[-1] = num[n] = -∞.所以只要从第一个数开始遍历,找到一个数nums[i]<nums[i-1],那么i-1就是所求的下标。

这个思路的时间复杂度为O(n)

代码如下:

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

此外还有二分查找的思想:如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧必包含一个局部最大值。将O(n)的复杂度降低为O(lgn)

代码如下:

public class Solution {    public int findPeakElement(int[] nums) {      int len = nums.length;      int right = len-1;      int left = 0;      int mid = (right+left)/2;            while(left<right){          if(nums[mid+1]<nums[mid]){              right = mid;          }else{              left = mid+1;          }           mid = (right+left)/2;      }      return left;    }}

参考博客:http://blog.csdn.net/u010367506/article/details/41943309

0 0
原创粉丝点击