leetcode 162. Find Peak Element

来源:互联网 发布:淘宝价格数字字体 编辑:程序博客网 时间:2024/05/17 04:26

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.

这道题就是寻找比邻居结点大的peek结点,我这里只是遍历一次即可。

代码如下:

/* * 我使用的的是最简单的办法 * */public class Solution{    public int findPeakElement(int[] nums)     {        if(nums==null || nums.length<=1)            return 0;        if(nums[0]>nums[1])            return 0;        else if(nums[nums.length-2] < nums[nums.length-1])            return nums.length-1;        else        {            for(int i=1;i<=nums.length-2;i++)            {                if(nums[i]>nums[i-1] && nums[i] > nums[i+1])                    return i;            }            return 0;        }    }}

下面是C++的做法,我这里是使用最简单的遍历方法做的

代码如下:

#include <iostream>#include <algorithm>#include <vector>using namespace std;class Solution {public:    int findPeakElement(vector<int>& nums)     {        if (nums.size() <= 1)            return 0;        if (nums[0] > nums[1])            return 0;        else if (nums[nums.size() - 1] > nums[nums.size() - 2])            return nums.size() - 1;        else        {            for (int i = 1; i <= nums.size() - 2; i++)            {                if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1])                    return i;            }            return 0;        }    }};
原创粉丝点击