该算法的原理是,在遍历数组的时,始终记录当前最大的元素和第二大的元素。示例代码:
package demo01 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 }
原文地址:http://blog.csdn.net/books1958/article/details/42752729