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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值