码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Find Peak Element

时间:2015-03-30 01:42:48      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目:
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: Find Peak Element

标签:leetcode

原文地址:http://blog.csdn.net/theonegis/article/details/44736033

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!