[leetcode]Find Peak Element

来源:互联网 发布:历年gdp三大产业数据 编辑:程序博客网 时间:2024/05/16 15:40

题目描述如下:

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.

题目十分形象,就是要找到顶峰的那个点。

这就要求了,该点的单边或两边数组都已排序(否则不会形成顶峰)。

在此基础上,可以使用二分法找点。想到这个思路的话就没有什么难度了,代码如下:

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

题目链接:https://leetcode.com/problems/find-peak-element/

0 0
原创粉丝点击