现在的位置: 首页 > 综合 > 正文

算法:寻找数组的第二大的元素(不排序、只循环一次)

2018年01月09日 ⁄ 综合 ⁄ 共 593字 ⁄ 字号 评论关闭

算法的原理是,在遍历数组的时,始终记录当前最大的元素和第二大的元素。示例代码:

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
}

抱歉!评论已关闭.