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.

    这道题是水题,注意边界条件就可以。 
    C++ Code:

class Solution {
public:
    int findPeakElement(const vector<int> &num) {
    if (num.size() == 1)
    {
        return 0;
    }
    else if (num.size() == 2)
    {
        return num[0] > num[1] ? 0 : 1;
    }

    int i = 1;
    for (; i < (num.size()-1); i++)
    {
        if ((num[i] > num[i - 1]) && (num[i] > num[i + 1])){
            return i;
        }
    }

    if ((num[0] > num[1])){
        return 0;
    }
    else if (num[i-1] < num[i])
    {
        return i;
    }

    return 0;
    }
};



本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5094315.html,如需转载请自行联系原作者
相关文章
|
索引
LeetCode 162. Find Peak Element
给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
109 0
LeetCode 162. Find Peak Element
|
人工智能 C++ Python
LeetCode 961. N-Repeated Element in Size 2N Array
LeetCode 961. N-Repeated Element in Size 2N Array
198 0
|
算法 容器
常用查找算法 find() find_if() adjacent_find() binary_search() count() count_if()
常用查找算法 find() find_if() adjacent_find() binary_search() count() count_if()
|
机器学习/深度学习 Java
HDOJ 2095 find your present (2)
HDOJ 2095 find your present (2)
117 0
HDOJ 2095 find your present (2)
Low Elements--AT
题目描述 Given is a permutation P1,…,PN of 1,…,N. Find the number of integers i (1≤i≤N) that satisfy the following condition: ·For any integer j (1≤j≤i), Pi≤Pj. Constraints ·1≤N≤2×105 ·P1,…,PN is a permutation of 1,…,N. ·All values in input are integers.
113 0
|
SQL Oracle 关系型数据库