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.

O(n)的方法很简单,甚至觉得不应该对应Medium难度。

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

后来发现要求O(logn)的方法。运算符优先级弄错了,鼓捣半天,>>的优先级小于四则运算的。另外一个点,mid+1是一定存在的,这个可以简化问题。

class Solution {
public:
    int findPeakElement(const vector<int> &num) {
        int low = 0;
        int up = num.size() - 1;
        while (low < up) {
            int mid1 = low + (up - low) / 2;
            int mid2 = mid1 + 1;
            if ((mid1 == 0 || num[mid1] > num[mid1-1]) && num[mid1] > num[mid2]) {
                return mid1;
            }
            if (num[mid1] > num[mid2]) {
                up = mid1;
            }
            else {
                low = mid2;
            }
        }
        
        return low;
    }
};

还有一种想法,只要元素个数大于2,那么mid-1和mid+1一定都存在。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值