Leetcode: 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.

思路:乍看这道题觉得没有任何难度。但是题目还有另外一个要求:Your solution should be in logarithmic complexity。这同时也给我们一个提示要求程序复杂度是对数级别的,那我们可以思考使用二分法或者类似的方法。由于代码比较简单,就不多作解释了,直接看代码!

C++代码:

class Solution
{
public:
    int findPeakElement(const vector<int> &num)
    {
        int left = 0;
        int right = num.size() - 1;
        int middle = right / 2;
        while (left < right)
        {
            middle = (left + right) / 2;
            if (num[middle] < num[middle + 1]) left = middle + 1;
            else right = middle;
        }
        //此时,left和right相等,返回left或者right都行
        return left;
    }
};

C#代码:

public class Solution
{
    public int FindPeakElement(int[] num)
    {
        int left = 0;
        int right = num.Length - 1;
        int middle = right / 2;
        while (left < right)
        {
            middle = (left + right) / 2;
            if (num[middle] < num[middle + 1]) left = middle + 1;
            else right = middle;
        }
        return left;
    }
}

Python代码:

class Solution:
    # @param num, a list of integer
    # @return an integer
    def findPeakElement(self, num):
        left = 0
        right = len(num) - 1
        middle = right / 2
        while left < right:
            middle = (left + right) / 2
            if num[middle] < num[middle + 1]:
                left = middle + 1
            else:
                right = middle
        return left

你可能感兴趣的:(LeetCode)