本文實例講述了Go語言算法之尋找數組第二大元素的方法。分享給大家供大家參考。具體如下:
該算法的原理是,在遍歷數組的時,始終記錄當前最大的元素和第二大的元素。示例代碼如下:
import (
"fmt"
)
func NumberTestBase() {
fmt.Println("This is NumberTestBase")
nums := []int{12, 24, 2, 5, 13, 8, 7}
fmt.Println("nums:", nums)
secondMax := getSecondMaxNum(nums)
fmt.Println("secondMax=", secondMax)
}
func getSecondMaxNum(nums []int) int {
length := len(nums)
if length == 0 {
panic("Slice nums cannot be 0-size.")
}
if length == 1 {
return nums[0]
}
var max, secondMax int
if nums[0] > nums[1] {
max = nums[0]
secondMax = nums[1]
} else {
max = nums[1]
secondMax = nums[0]
}
for i := 2; i < len(nums); i++ {
if nums[i] > secondMax {
if nums[i] <= max {
secondMax = nums[i]
} else {
secondMax, max = max, nums[i]
}
}
}
return secondMax
}
希望本文所述對大家的Go語言程序設計有所幫助。