首页 > 其他 > 详细

[LeetCode 162.] Find Peak Element

时间:2021-01-22 22:43:45      阅读:31      评论:0      收藏:0      [点我收藏+]

LeetCode 162. Find Peak Element

题目描述

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

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

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

Constraints:

  • 1 <= nums.length <= 1000
  • -231 <= nums[i] <= 231 - 1
  • nums[i] != nums[i + 1] for all valid i.

解题思路

线性查找的极端情况是单峰且在另一端;加入方向优化之后能缓解这种情况,最差是单峰出现在最中间;
数据量再上去之和还可以考虑继续加入从中间到两端的查找,四路并行查找 —— 优点类似于钻山隧道施工的意思。

另一种解决思路是O(logN)的二分查找算法,不是很直观能想到。

  1. 先找中间点,如果恰好是一个峰,当然可以直接返回;
  2. 如果不是峰,则在较大的相邻元素一侧继续搜寻。

为什么是到大的一段去搜,很简单的一个例子就能说明:如[1,2,3]这种只有单峰的极端情况,只有在较大侧才能找到峰。

参考代码

/*
 * @lc app=leetcode id=162 lang=cpp
 *
 * [162] Find Peak Element
 */

// @lc code=start
class Solution {
public:
/*
    // nums[i] != nums[i + 1] for all valid i.
    int findPeakElement(vector<int>& nums) {
        if (nums.empty()) return -1;
        if (nums.size() == 1) return 0;
        int i = 0, j = nums.size() - 1;
        if (nums[i] > nums[i+1]) return i;
        if (nums[j-1] < nums[j]) return j;
        i++; j--;
        while (i <= j) {
            if (nums[i-1] < nums[i] && nums[i] > nums[i+1]) return i;
            if (nums[j-1] < nums[j] && nums[j] > nums[j+1]) return j;
            i++; j--;
        }
        assert(false);
        return -1;
    } // AC, direction-optimzed linear search, O(N)
*/
    // nums[i] != nums[i + 1] for all valid i.
    int findPeakElement(vector<int>& nums) {
        if (nums.empty()) return -1;
        if (nums.size() == 1) return 0;
        int l = 0, r = nums.size() - 1;
        while (l < r) {
            int m = l + (r - l) / 2;
            if (nums[m] < nums[m+1]) { // nums.size()==2 OK
                l = m + 1;
            } else {
                r = m;
            }
        }
        return l;
    } // AC, binary search, O(logN)
};
// @lc code=end

[LeetCode 162.] Find Peak Element

原文:https://www.cnblogs.com/zhcpku/p/14315158.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!