LeetCode 162. Find Peak Element(查找峰值)

来源:互联网 发布:菊花插件dbm数据下载 编辑:程序博客网 时间:2024/06/03 07:29

原题网址:https://leetcode.com/problems/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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

方法一:全局扫描。

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

方法二:二分法。

public class Solution {    public int findPeakElement(int[] nums) {        int i=0, j=nums.length-1;        while (i<j) {            int m = (i+j)/2;            if (nums[m] > nums[m+1]) j=m; else i=m+1;        }        return i;    }}


0 0
原创粉丝点击