162. Find Peak Element**

162. Find Peak Element**

https://leetcode.com/problems/find-peak-element/

题目描述

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 
Explanation: Your function can return either index number 1 where the peak element is 2, 
             or index number 5 where the peak element is 6.

Note:

  • Your solution should be in logarithmic complexity.

C++ 实现 1

先看 O ( N ) O(N) 的方法:

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

C++ 实现 2

参考 Find the maximum by binary search (recursion and iteration) 完成 Binary Search 求解的方法.

在这里插入图片描述

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

C++ 实现 3

看完 C++ 实现 2 的思路, 实际上由于序列是分段有序的, 那么就只要查找第一个满足 nums[i] > nums[i + 1] 的数即可. 更简洁的 O ( N ) O(N) 代码:

class Solution {
public:
    int findPeakElement(const vector<int> &num) {
        for(int i = 1; i < num.size(); i ++) {
            if(num[i - 1] > num[i])
                return i-1;
        }
        return num.size() - 1;
    }
};
发布了227 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/103987489
今日推荐