使用Golang查找数组中的峰

问题描述 投票:1回答:1

我正在尝试找到数组的峰值。我已经看过一些解决问题的教程,但是没有使用golang的教程。我的问题是,当此数组中的8、8值达到平稳状态时:[13、9,-2,-5、8、8、14,-2,-3]返回了错误的峰。预期的峰值应为14。

我从此算法开始:

type PosPeaks struct {
    Pos   []int
    Peaks []int
}
func PickPeaks(array []int) PosPeaks {
    var p PosPeaks
    if len(array) == 0 {
        return p
    }

    // build a difference array, that indicates the change between the
    // ith element and the ith+1 element. +1 if positive change, 0 if 
    // no change and -1 if negative change
    diff := []int{}
    for i := 0; i < len(array)-1; i++ {
        if array[i] < array[i+1] {
            diff = append(diff, 1)
        } else if array[i] == array[i+1] {
            diff = append(diff, 0)
        } else {
            diff = append(diff, -1)
        }
    }

    // Now walk through the difference array, looking at the 
    // changes
    for i := 0; i < len(array)-2; i++ {

        // if it goes uphill and then down, this is a peak to record
        if diff[i] == 1 && diff[i+1] == -1 {
            p.Pos = append(p.Pos, i+1)
            p.Peaks = append(p.Peaks, array[i+1])
        }

        // If it goes uphill, then plateaus, then look out further to 
        // see if it ever goes downhill. If so, call this a peak.
        if diff[i] == 1 && diff[i+1] == 0 {
            for j := i + 1; j < len(array)-1; j++ {
                if diff[j] == -1 {
                    p.Pos = append(p.Pos, i+1)
                    p.Peaks = append(p.Peaks, array[i+1])
                }

            }
        }
    }
    return p
}
go find position solution
1个回答
0
投票

我认为我们需要更多背景信息来理解问题的约束。实际上,这个简单的解决方案就足够了,但是我怀疑您的问题有更多的定义您没有提到:

package main

import (
    "fmt"
)

func main() {
    fmt.Printf("Hello, %d", findMaxPeak([]int{13, 9, -2, -5, 8, 8, 14, -2, -3}))
}

func findMaxPeak(s []int) int {
    var p []int
    var l = len(s)
    for i := 1; i < l-1; i++ {
        if s[i-1] < s[i] && s[i] > s[i+1] {
            p = append(p, s[i])
        }
    }
    l = len(p)
    if len(p) == 1 {
        return p[0]
    }
    var max int
    for i := 0; i < l; i++ {
        if p[i] > p[i+1] {
            max = p[i]
            continue
        }
        max = p[i+1]
    }
    return max
}
© www.soinside.com 2019 - 2024. All rights reserved.