75. Find Peak Element(二分法)

本文介绍了一种使用二分查找法在数组中寻找峰值元素的方法。针对不同条件下的数组(如先升后降或任意增减模式),提供了两种实现方案。通过不断缩小搜索范围,最终定位到峰值元素的位置。

LintCode

Description

There is an integer array which has the following features:

  • The numbers in adjacent positions are different.
  • A[0] < A[1] && A[A.length - 2] > A[A.length - 1].

We define a position P is a peak if:

A[P] > A[P-1] && A[P] > A[P+1]

Find a peak element in this array. Return the index of the peak.

 Notice
  • It's guaranteed the array has at least one peak.
  • The array may contain multiple peeks, find any of them.
  • The array has at least 3 numbers in it.
Example

Given [1, 2, 1, 3, 4, 5, 7, 6]

Return index 1 (which is number 2) or 6 (which is number 7)

Challenge 

Time complexity O(logN)

Solution

这道题也是经典二分法例题的变形,由于mid位置的取值总共分为四种情况,上升(向右找峰),下降(向左找峰),峰值(返回峰值),谷值(向两边都可以找到峰)。由题意至少三个数而且必有峰,因此一定可以在缩小到三个数的时候找到峰值。可以用二分法缩小范围解决这个问题。

Java

public class Solution {
    /*
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    public int findPeak(int[] A) {
        // write your code here
        int start = 0, end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            //如果上升,右边至少一个峰
            if (A[mid - 1] < A[mid] && A[mid] < A[mid + 1]) {
                start = mid;
            } else if (A[mid - 1] > A[mid] && A[mid] > A[mid + 1]) {
                //如果下降,左边至少一个峰
                end = mid;
            } else if (A[mid - 1] < A[mid] && A[mid] > A[mid + 1]) {
                //如果是峰,则返回mid
                return mid;
            } else {
                //如果是谷,则左右都至少有一个峰,向左向右缩小范围均可
                //end = mid;
                start = mid;
            }
        }
        return -1;
    }
}

-------------------------------------------------------------------------

LeetCode

Description

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.

Solution

LeetCode这道题不像LintCode中的那道题有规定至少三个元素,并且先增后减(即一定有峰)的情况。因此存在一个元素或者单调增/减的情况。解法如下:(此解法也适用LintCode,思想就是不断缩小范围找到最大值)

class Solution {
    public int findPeakElement(int[] nums) {
        if (nums == null || nums.length == 0) {  
            return -1;  
        }  
        int start = 0, end = nums.length - 1;       // 数组长度至少为1  
        //当数组中至少有3个数时才进入循环,因此mid不会有越界的情况发生  
        while (start + 1 < end) {  
            int mid = start + (end - start) / 2;  
            //如果是下降的,则将向左找峰  
            if (nums[mid] < nums[mid - 1]) {  
                end = mid;  
            } else if (nums[mid] < nums[mid + 1]) {  
                //如果是上升的,则向右找峰  
                start = mid;  
            } else {  
                //如果是峰值则返回mid,或者向左/向右缩小范围  
                //return mid;  
                end = mid;  
            }  
        }  
        //范围缩小到两个数时取出较大的,则为峰  
        if (nums[start] < nums[end]) {  
            return end;  
        } else {   
            return start;  
        }  
    }
}

二分法是一种用于数值计算的迭代算法,用于在一个区间内寻找函数的根。其基本思想是将区间一分为二,然后根据函数在区间两端点的取值情况,确定根位于哪一半区间内,然后继续在该子区间内进行二分,直到满足所需的精度要求。 以下是使用Python实现二分法求解函数 $f(x)=x^3 + x^2 - 1$ 在区间 $[0,1]$ 上的根,精度 $E = 0.0005$ 的代码: ```python def f(x): return x**3 + x**2 - 1 # 二分法函数 def bisection_method(a, b, E): # 检查区间两端点的函数值是否异号 if f(a) * f(b) >= 0: raise ValueError("函数在区间两端点的函数值必须异号。") while (b - a) / 2 > E: # 计算区间的中点 c = (a + b) / 2 # 检查中点是否为根 if f(c) == 0: return c # 根据函数值的符号更新区间 elif f(c) * f(a) < 0: b = c else: a = c # 返回最终的近似根 return (a + b) / 2 # 定义区间和精度 a = 0 b = 1 E = 0.0005 # 调用二分法函数求解根 root = bisection_method(a, b, E) print(f"函数 f(x)=x^3 + x^2 - 1 在区间 [0,1] 上的根,精度 E = 0.0005 的近似值为: {root}") ``` ### 代码解释: 1. **定义函数 $f(x)$**:定义了要求根的函数 $f(x)=x^3 + x^2 - 1$。 2. **二分法函数 `bisection_method`**:该函数接受区间的左右端点 `a` 和 `b`,以及精度 `E` 作为参数。在函数内部,首先检查区间两端点的函数值是否异号,如果不是则抛出异常。然后在循环中,不断将区间一分为二,根据中点的函数值更新区间,直到区间的长度小于等于 $2E$。最后返回区间的中点作为近似根。 3. **调用二分法函数**:定义区间 $[0,1]$ 和精度 $E = 0.0005$,并调用 `bisection_method` 函数求解根。最后打印出近似根的值。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值