LeetCode 162 Find Peak Element

本文介绍了一种寻找数组中峰值元素的方法,峰值元素定义为大于其邻居的元素。文章提供了两种解决方案,一种是线性搜索,复杂度为O(n),另一种是二分搜索,复杂度为O(logn)。

Problem:

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.

Your solution should be in logarithmic complexity.

Summary:

找到数组中的局部最大数。

Solution:

1. 顺序查找:最直接的方法,复杂度为O(n)

 1 class Solution {
 2 public:
 3     int findPeakElement(vector<int>& nums) {
 4         int len = nums.size();
 5         if (len == 1) {
 6             return 0;
 7         }
 8         
 9         for (int i = 0; i < len; i++) {
10             if (!i && nums[i] > nums[i + 1] || 
11                 i == len - 1 && nums[i] > nums[i - 1] ||
12                 nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
13                     return i;
14                 }
15         }
16         
17         return -1;
18     }
19 };

2. 二分查找:首先找到整体的中间值m,若m符合局部最大条件则返回m,否则若nums[m - 1] > nums[m]则在[0, m - 1]中查找。因为数组左边和右边为负无穷,所以在这种情况下[0, m - 1]中一定存在一个局部最大值。这种方法复杂度为O(logn)。

 1 class Solution {
 2 public:
 3     int findPeakElement(vector<int>& nums) {
 4         int len = nums.size();
 5         if (len == 1) {
 6             return 0;
 7         }
 8         
 9         int l = 0, r = len - 1;
10         while (l <= r) {
11             int m = (l + r) / 2;
12             if ((!m || nums[m] >= nums[m - 1]) &&
13                 (m == len - 1 || nums[m] >= nums[m + 1])) {
14                     return m;
15                 }
16             if (m && nums[m] < nums[m - 1]) {
17                 r = m - 1;
18             }   
19             else {
20                 l = m + 1;
21             }
22         }
23         
24         return -1;
25     }
26 };

二分查找的简略写法:

 1 class Solution {
 2 public:
 3     int findPeakElement(vector<int>& nums) {
 4         int len = nums.size();
 5         if (len == 1) {
 6             return 0;
 7         }
 8         
 9         int l = 0, r = len - 1;
10         while (l < r) {
11             int m = (l + r) / 2;
12             if (nums[m] > nums[m + 1]) {
13                 r = m;
14             }
15             else {
16                 l = m + 1;
17             }
18         }
19         
20         return r;
21     }
22 };

 

转载于:https://www.cnblogs.com/VickyWang/p/6242160.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值