leetcode-java-162. 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.

 */
/*
此题表面是看找出比旁边两个值大就可以,也就是如思路一。但是复杂度是o(n)
但是其实找到数组中的最大值就可以了,则用二分查找就可以了。复杂度是o(lgn)
 */
// 思路一:
// 遍历来找到nums[i],但是只打败了2%,就像看看其他人的想法
 public class Solution {
      public int findPeakElement(int[] nums) {
          int len = nums.length,
              i = 0;

          if(len < 2) {
              return 0;
          }

          for(;i < len;i++) {
              if(i == 0 && nums[0] > nums[1]){
                 return 0;
             }else if(i == len-1 && nums[i] > nums[i-1]) {
                 return i;
             } else if(nums[i] > nums[i+1] && nums[i] > nums[i-1]){
                 return i;
             }
          }
          return 0;
      }
  }
  // 思路二:二分查找
  public class Solution {
    public int findPeakElement(int[] nums) {
        int len = nums.length,
            left = 0,
            right = len - 1;

        while(left < right) {
            int mid = left + (right-left)/2;

            if(nums[mid] < nums[mid+1]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }

        return left;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值