题解 | #寻找峰值#二分法 如果相邻右边的值小于中间值那左侧必有波峰 相反 右侧必有波峰

寻找峰值

http://www.nowcoder.com/practice/fcf87540c4f347bcb4cf720b5b350c76



public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型一维数组 
     * @return int整型
     */
    public int findPeakElement (int[] nums) {
        // write code here
        //思路一 直接遍历数组 找到满足峰值条件的索引 最笨的方法
        //思路二 二分法 如果相邻右边的值小于中间值那左侧必有波峰 相反 右侧必有波峰
        int beginIndex = 0;
        int endIndex = nums.length - 1;
        while(beginIndex < endIndex){
            int midIndex = beginIndex + (endIndex - beginIndex) / 2;
            if(nums[midIndex] > nums[midIndex + 1]){
                endIndex = midIndex;
            } else {
                beginIndex = midIndex + 1;
            }
        }
        return beginIndex;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务