zoukankan      html  css  js  c++  java
  • 返回数值数组的“峰值”(或局部最大值)的位置和值

    题目描述:

    # In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array.
    #
    # For example, the array arr = [0, 1, 2, 5, 1, 0] has a peak at position 3 with a value of 5 (since arr[3] equals 5).
    #
    # The output will be returned as an object with two properties: pos and peaks. Both of these properties should be arrays. If there is no peak in the given array, then the output should be {pos: [], peaks: []}.
    #
    # Example: pickPeaks([3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]) should return {pos: [3, 7], peaks: [6, 3]} (or equivalent in other languages)
    #
    # All input arrays will be valid integer arrays (although it could still be empty), so you won't need to validate the input.
    #
    # The first and last elements of the array will not be considered as peaks (in the context of a mathematical function, we don't know what is after and before and therefore, we don't know if it is a peak or not).
    #
    # Also, beware of plateaus !!! [1, 2, 2, 2, 1] has a peak while [1, 2, 2, 2, 3] does not. In case of a plateau-peak, please only return the position and value of the beginning of the plateau. For example: pickPeaks([1, 2, 2, 2, 1]) returns {pos: [1], peaks: [2]} (or equivalent in other languages)


    我的解答:
      
    def pickPeaks(lisArr):
    res = dict()
    res['pos'] = list()
    res['peak'] = list()
    key = 0
    count = 0
    for i in range(1, len(lisArr) - 1):
    if lisArr[i] > lisArr[i - 1]:
    key += 1
    if lisArr[i] > lisArr[i + 1]:
    key += 1
    if lisArr[i] == lisArr[i + 1]:
    count += 1
    continue
    if key == 2:
    res['pos'].append(i - count)
    res['peak'].append(lisArr[i])
    key = 0
    count = 0
    return res




  • 相关阅读:
    c++输入输出,保留几位小数
    算法训练 旅行家的预算
    算法训练 拦截导弹(最长递增子序列和最长递减子序列问题,输入回车时停止输入)
    算法训练 字符串比较
    关于新博客的转移
    关于在对象内部访问实例变量的方式选择
    动态计算文本宽度和高度
    工作将近三个月的总结(未完持续)
    ViewController的.m文件代码布局规范
    Objective-C学习之Runtime
  • 原文地址:https://www.cnblogs.com/wlj-axia/p/12737247.html
Copyright © 2011-2022 走看看