Leetcode_162_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.

题意:找到一组数的最大值
思路:遍历数组,如果大于左边和右边的数,立刻返回当前的index
坑:如果数组只有一个数的话,直接返回0即可。
代码:

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

            if(nums[i] > nums[i-1] && nums[i] > nums[i+1]) return i;
        }

        return i;
    }
};

看了看讨论区又一次感到智商被碾压了,使用了二分搜索来实现。
先看中间结点是否比右边大,如果大则极大值一定在左边,如果小,那就一定在右边。
原因:假设比右边大,在比较左边的,如果左边的比中间的小,那中间的就是结果,就让中间等于左边的,继续比较下去。。。

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int l = 0, r = nums.size() - 1;
        while(l < r)
        {
            int mid = (r + l)/2;
            if(nums[mid] > nums[mid+1]) r = mid;
            else l = mid + 1;
        }

        return l;
    }
};

你可能感兴趣的:(LeetCode)