Find Peak Element

来源:互联网 发布:把高中老师给睡了知乎 编辑:程序博客网 时间:2024/05/17 03:30

一、问题描述

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.

二、思路

本题意在找出排序数组中当前元素比下一个元素大的元素,非常简单,遍历即可,而且当存在多个这样的数时,不需要返回其他值。

三、代码

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int peak = 0 , i = 0;
        if(nums.size() == 0) return 0;
        for(i = 0; i < nums.size() - 1; ++i){
            if(nums[i] > nums[i + 1])
                break;
        }
        return i;
    }
};

0 0