在一系列值中找到局部最大值 [英] Find the local maxima in a sequence of values

查看:38
本文介绍了在一系列值中找到局部最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用哪种算法在长度为10的随机生成的值数组中找到局部最大值?

What algorithm can we use to find the local maxima in a randomly generated value array of length 10?

我目前的策略是将数组分成3个并找到每个子集数组的最大元素,但这不包括所有最大值.

My current strategy is to break the array into 3 and find the maximum element of each subset array, but that does not include all the maxima.

理想情况下,我希望将第一个点也标识为局部最大值,不应从左起第三个红色标记为局部最大值.

Ideally, I would like the first point to also be identified as a local maximum, and the third red from left should not be marked as such.

推荐答案

只需遍历所有索引,然后将该元素与任一侧的两个元素进行比较,而无需检查其是否在边缘.

Just go through all the indices and compare that element to the two elements on either side, skipping the check if it's on the edge.

伪代码:

for each index
  if     (index == 0              or array[index-1] < array[index])
     and (index == array.length-1 or array[index+1] < array[index])
  {
    store index
  }

这篇关于在一系列值中找到局部最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆